Skip to content

Commit 8c0027e

Browse files
authored
Create swapping-nodes-in-a-linked-list.cpp
1 parent 659ec6f commit 8c0027e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode() : val(0), next(nullptr) {}
10+
* ListNode(int x) : val(x), next(nullptr) {}
11+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
12+
* };
13+
*/
14+
class Solution {
15+
public:
16+
ListNode* swapNodes(ListNode* head, int k) {
17+
ListNode *left = nullptr, *right = nullptr;
18+
for (auto curr = head; curr; curr = curr->next) {
19+
if (right) {
20+
right = right->next;
21+
}
22+
if (--k == 0) {
23+
left = curr;
24+
right = head;
25+
}
26+
}
27+
swap(left->val, right->val);
28+
return head;
29+
}
30+
};

0 commit comments

Comments
 (0)