Skip to content

Commit 94fe45f

Browse files
Create swapping_nodes_in_linked_list.cpp
1 parent 81c9420 commit 94fe45f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

swapping_nodes_in_linked_list.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* swapNodes(ListNode* head, int k) {
14+
if(k == 0) return head;
15+
16+
ListNode *slow, *kthBegin, *fast = head;
17+
18+
for(int i = 0; i < k; i++) {
19+
kthBegin = fast;
20+
fast = fast->next;
21+
}
22+
23+
slow = head;
24+
while(fast) {
25+
slow = slow->next;
26+
fast = fast->next;
27+
}
28+
cout<<kthBegin->val<<" "<<slow->val<<" ";
29+
swap(slow->val, kthBegin->val);
30+
31+
return head;
32+
33+
}
34+
};

0 commit comments

Comments
 (0)