File tree Expand file tree Collapse file tree 3 files changed +82
-6
lines changed
solution/1700-1799/1721.Swapping Nodes in a Linked List Expand file tree Collapse file tree 3 files changed +82
-6
lines changed Original file line number Diff line number Diff line change @@ -123,10 +123,35 @@ class Solution {
123
123
}
124
124
```
125
125
126
- ### ** ...**
127
-
128
- ```
126
+ ### ** C++**
129
127
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
+ };
130
155
```
131
156
132
157
<!-- tabs:end -->
Original file line number Diff line number Diff line change @@ -92,10 +92,35 @@ class Solution {
92
92
}
93
93
```
94
94
95
- ### ** ...**
96
-
97
- ```
95
+ ### ** C++**
98
96
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
+ };
99
124
```
100
125
101
126
<!-- tabs:end -->
Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments