aboutsummaryrefslogtreecommitdiff
path: root/swap_node_linked_list.c
blob: 42db7425f681561c09796f476c190438e929526a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// 1721. Swapping Nodes in a Linked List
#include <stdlib.h>

/*
 * given the 'head' of a linked list, and a an integer 'k', return
 * the head of the linked list after swapping the values of the
 * k'th node from the beginning and the k'th node from the end
 */

struct ListNode {
  int val;
  struct ListNode *next;
};

int countNode(struct ListNode *head) {
  int d = 0;
  struct ListNode *tmp = head;
  while (tmp) {
    d++;
    tmp = tmp->next;
  }
  return d;
}

struct ListNode *swapNodes(struct ListNode *head, int k) {
  int total = countNode(head);
  if (total == 1)
    return head;
  if (total == 2) {
    struct ListNode *tmp = head->next;
    tmp->next = head;
    head->next = NULL;
    head = tmp;
    return head;
  }
  int p = total - k + 1, i = 1;
  struct ListNode *node1 = head;
  struct ListNode *ptr1 = NULL;
  struct ListNode *post1 = NULL;
  while (i < k) {
    ptr1 = node1;
    node1 = node1->next;
    i++;
  }
  post1 = node1->next;
  i = 1;
  struct ListNode *node2 = head;
  struct ListNode *ptr2 = NULL;
  struct ListNode *post2 = NULL;
  while (i < p) {
    ptr2 = node2;
    node2 = node2->next;
    i++;
  }
  post2 = node2->next;
  if (node1 == node2)
    return head;
  if (p - k == 1) {
    ptr1->next = node2;
    node2->next = node1;
    node1->next = post2;
    return head;
  }
  if (k - p == 1) {
    ptr2->next = node1;
    node1->next = node2;
    node2->next = post1;
    return head;
  }
  if (k == 1) {
    node2->next = post1;
    head = node2;
    ptr2->next = node1;
    node1->next = NULL;
  } else if (k == total) {
    node1->next = post2;
    head = node1;
    ptr1->next = node2;
    node2->next = NULL;
  } else {
    ptr1->next = node2;
    node2->next = post1;
    ptr2->next = node1;
    node1->next = post2;
  }
  return head;
}