Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
自己的方法是将两个reverse,再利用递归,做麻烦了。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* next = swapPairs(head->next->next);
ListNode* prev = NULL;
ListNode* node = head;
for (int i = 0; i < 2; i++) {
ListNode* tmp = node->next;
node->next = prev;
prev = node;
node = tmp;
}
head->next = next;
return prev;
}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* next = swapPairs(head->next->next);
ListNode* node = head->next;
head->next = next;
node->next = head;
return node;
}
};