-
Notifications
You must be signed in to change notification settings - Fork 0
/
1721. Swapping Nodes in a Linked List.cpp
43 lines (43 loc) · 1.27 KB
/
1721. Swapping Nodes in a Linked List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode* tmp = head;
ListNode* first = new ListNode;
ListNode* second = new ListNode;
ListNode* answer = new ListNode;
ListNode* Head_answer = answer;
int i = 1, size = 0;
while(tmp != NULL){
if(i == k) first->val = tmp->val;
++i;
++size;
tmp = tmp->next;
}
tmp = head;
for(int j = 1; j<=size-k+1; ++j){
if(j == size-k+1) second->val = tmp->val;
if(tmp == NULL) break;
tmp = tmp->next;
}
tmp = head;
for(int j = 1; j <= size; ++j){
if(tmp == NULL) break;
if(j == k) answer->next = second;
else if(j == size-k+1) answer->next = first;
else answer->next = tmp;
tmp = tmp->next;
answer = answer->next;
}
return Head_answer->next;
}
};