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.
解法一:递归
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* new_head = head->next;
head->next = swapPairs(new_head->next);
new_head->next = head;
return new_head;
}
};
解法二:非递归
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* new_head = NULL;
ListNode** pp = &new_head;
while(head != NULL){
if(head->next == NULL){
*pp = head;
break;
}
else{
*pp = head->next;
head->next = (*pp)->next;
(*pp)->next = head;
pp = &(head->next);
head = head->next;
}
}
return new_head;
}
};