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.
这个题目我使用了下递归,把自己绕死了,而且被各种指针指空导致的问题烦死了,各种补洞出来的AC代码,如下:
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *first = head;
ListNode *second = head->next;
first->next = second->next;
second->next = first;
head = second;
if(first->next == NULL)
return head;
if(first->next->next != NULL)
{
second = first->next->next;
swap(first, second);
}
return head;
}
void swap(ListNode *first, ListNode *second)
{
if(second == NULL)
return;
if(second->next != NULL)
{
swap(first->next->next, second->next->next);
}
first->next->next = second->next;
second->next = first->next;
first->next = second;
}
};