Skip to content

Commit 46a9ef3

Browse files
authored
Merge pull request #33 from Frisk0316/Frisk0316-patch-33
Create 1721. Swapping Nodes in a Linked List
2 parents a2ac14a + 2732726 commit 46a9ef3

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// 2023.05.15 Leetcode Daily Challenge
2+
// wrote by C++
3+
// Runtime beats 90.85%
4+
// Memory beats 70.53%
5+
6+
7+
/**
8+
* Definition for singly-linked list.
9+
* struct ListNode {
10+
* int val;
11+
* ListNode *next;
12+
* ListNode() : val(0), next(nullptr) {}
13+
* ListNode(int x) : val(x), next(nullptr) {}
14+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
15+
* };
16+
*/
17+
18+
class Solution {
19+
public:
20+
ListNode* swapNodes(ListNode* head, int k) {
21+
ListNode *n1 = nullptr;
22+
ListNode *n2 = nullptr;
23+
24+
for (auto p = head; p != nullptr; p = p->next) {
25+
n2 = n2 == nullptr ? nullptr : n2->next;
26+
if (--k == 0) {
27+
n1 = p;
28+
n2 = head;
29+
}
30+
}
31+
32+
// The problem description specifically asks to swap values, not nodes themselves.
33+
swap(n1->val, n2->val);
34+
return head;
35+
}
36+
};

0 commit comments

Comments
 (0)