-
Notifications
You must be signed in to change notification settings - Fork 2
/
leetcode24.cpp
51 lines (50 loc) · 1.15 KB
/
leetcode24.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
44
45
46
47
48
49
50
51
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL)
return NULL;
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* next = cur->next;
if (next == NULL)
return cur;
ListNode* ans = next;
while (next) {
if (prev)
prev->next = next;
cur->next = next->next;
next->next = cur;
prev = cur;
cur = cur->next;
if (!cur)
return ans;
next = cur->next;
}
return ans;
}
};
class Solution2 {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL)
return NULL;
ListNode** cur = &head;
ListNode* a = NULL;
ListNode* b = NULL;
while ((a = *cur) && (b = a->next)) {
a->next = b->next;
b->next = a;
*cur = b;
cur = &(a->next);
}
return head;
}
};