-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24. Swap Nodes in Pairs.txt
59 lines (50 loc) · 1.89 KB
/
24. Swap Nodes in Pairs.txt
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Îïòèìàëüíûé êîä.
ListNode* swapPairs(ListNode* head) {
ListNode dummy(0, head); //Ñîçäà¸ì -1 óçåë
ListNode *pre = &dummy, *first = head;//Äîáàâëÿåì 2 óêàçàòåëÿ íà -1 è 1 óçåë
while (first && first->next) {//Ïîêà 1ûé è 2îé óçåë ñóùåñòâóþò
ListNode *second = first->next;//Èíèöèàëèçàöèÿ âòîðîãî óçëà
ListNode *nextPair = second->next;//Èíèöèàëèçàöèÿ ñëåäóþùåé ïàðû
pre->next = second;//next -1îãî óçëà ìåíÿåì íà 2îé óçåë âìåñòî 1îãî
first->next = nextPair;//next 1îãî óçëà ìåíÿåì íà 3èé óçåë âìåñòî 2îãî
second->next = first;//next âòîðîãî óçëà ìåíÿåì íà 1ûé âìåñòî 3åãî
pre = first;//Ïîäãîòîâêà ê ñëåäóþùåé èòåðàöèè. pre òåïåðü 2îé óçåë
first = nextPair;//Ïîäãîòîâêà ê ñëåäóþùåé èòåðàöèè. first òåïåðü 3èé óçåë
}
return dummy.next;//Âîçâðàò 1 óçëà
}
//Ìîé êîä. Ïðîñòî ïîìåíÿòü óêàçàòåëè ìåñòàìè è âñå.
/**
* 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* swapPairs(ListNode* head) {
if(head == NULL)
return {};
if(head->next == NULL)
return head;
ListNode *previousNode = head;
ListNode *secondNude = previousNode->next;
ListNode *answer = secondNude;
ListNode *lastNode = previousNode;
while (previousNode != NULL && previousNode->next != NULL) {
secondNude = previousNode->next;
ListNode *temp = secondNude->next;
secondNude->next = previousNode;
if (previousNode != head)
lastNode->next = secondNude;
previousNode->next = temp;
lastNode = previousNode;
previousNode = temp;
}
return answer;
}
};