Skip to content

Commit 8b63128

Browse files
authored
feat: add cpp solution to lc problem: No.1721 (#786)
No.1721.Swapping Nodes in a Linked List
1 parent 9010e98 commit 8b63128

File tree

3 files changed

+82
-6
lines changed

3 files changed

+82
-6
lines changed

solution/1700-1799/1721.Swapping Nodes in a Linked List/README.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,10 +123,35 @@ class Solution {
123123
}
124124
```
125125

126-
### **...**
127-
128-
```
126+
### **C++**
129127

128+
```cpp
129+
/**
130+
* Definition for singly-linked list.
131+
* struct ListNode {
132+
* int val;
133+
* ListNode *next;
134+
* ListNode() : val(0), next(nullptr) {}
135+
* ListNode(int x) : val(x), next(nullptr) {}
136+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
137+
* };
138+
*/
139+
class Solution {
140+
public:
141+
ListNode* swapNodes(ListNode* head, int k) {
142+
ListNode *p1 = head;
143+
for (int i = 1; i < k; i++)
144+
p1 = p1->next;
145+
ListNode* slow = head, *fast = p1->next;
146+
147+
while (fast) {
148+
fast = fast->next;
149+
slow = slow->next;
150+
}
151+
swap(slow->val, p1->val);
152+
return head;
153+
}
154+
};
130155
```
131156
132157
<!-- tabs:end -->

solution/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,35 @@ class Solution {
9292
}
9393
```
9494

95-
### **...**
96-
97-
```
95+
### **C++**
9896

97+
```cpp
98+
/**
99+
* Definition for singly-linked list.
100+
* struct ListNode {
101+
* int val;
102+
* ListNode *next;
103+
* ListNode() : val(0), next(nullptr) {}
104+
* ListNode(int x) : val(x), next(nullptr) {}
105+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
106+
* };
107+
*/
108+
class Solution {
109+
public:
110+
ListNode* swapNodes(ListNode* head, int k) {
111+
ListNode *p1 = head;
112+
for (int i = 1; i < k; i++)
113+
p1 = p1->next;
114+
ListNode* slow = head, *fast = p1->next;
115+
116+
while (fast) {
117+
fast = fast->next;
118+
slow = slow->next;
119+
}
120+
swap(slow->val, p1->val);
121+
return head;
122+
}
123+
};
99124
```
100125
101126
<!-- tabs:end -->
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
ListNode *p1 = head;
15+
for (int i = 1; i < k; i++)
16+
p1 = p1->next;
17+
ListNode* slow = head, *fast = p1->next;
18+
19+
while (fast) {
20+
fast = fast->next;
21+
slow = slow->next;
22+
}
23+
swap(slow->val, p1->val);
24+
return head;
25+
}
26+
};

0 commit comments

Comments
 (0)