-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathSwapping Nodes in a Linked List.cpp
55 lines (33 loc) · 1.21 KB
/
Swapping Nodes in a Linked List.cpp
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
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
// declare a dummy node
ListNode* dummy = new ListNode(0);
// point dummy -> next to head
dummy -> next = head;
// declare a tail pointer and point to dummy
ListNode* tail = dummy;
// move the curr pointer (k - 1) times
// this will maintain a gap of (k - 1) between curr and tail pointer
ListNode* curr = head;
while(k > 1)
{
curr = curr -> next;
k--;
}
// store the address in start pointer
ListNode* start = curr;
// maintaing a gap of (k - 1) between curr and tail, move both pointer
while(curr)
{
tail = tail -> next;
curr = curr -> next;
}
// store the address of kth node from end
ListNode* end = tail;
// swap the values
swap(start -> val, end -> val);
// dummy -> next will be head
return dummy -> next;
}
};