0%

24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

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
/**
* 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 == nullptr || head->next == nullptr) return head;
ListNode* point = head;
ListNode* pre = new ListNode();
pre->next = head;
ListNode* newHead = head->next;
while(point != nullptr && point->next != nullptr)
{
ListNode* n2 = point->next;
ListNode* next = n2->next;
n2->next = point;
point->next = next;
pre->next = n2;
pre = point;
point = next;
}
return newHead;
}
};
discussion 递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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 == nullptr || head->next ==nullptr) return head;
ListNode* n = head->next;
head->next = swapPairs(head->next->next);
n->next = head;
return n;
}
};