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.
ListNode* swapPairs(ListNode* head) {
ListNode *p1 = head, *p2;
int tmp;
while(p1) {
p2 = p1->next;
if (p2) {
tmp = p1->val;
p1->val = p2->val;
p2->val = tmp;
p1 = p1->next;
}
p1 = p1->next;
}
return head;
}
ListNode* swapPairs(ListNode* head) {
ListNode *p1 = head, *p2, *tmp;
if (p1 && p1->next) {
head = head->next;
}
tmp = head;
while(p1) {
p2 = p1->next;
if (p2) {
p1->next = p2->next;
p2->next = p1;
if (tmp != head)
tmp ->next = p2;
tmp = p1;
}
p1 = p1->next;
}
return head;
}
ListNode* swapPairs(ListNode* head) {
ListNode* p1;
if(head && head->next){
p1 = head->next;
head->next = swapPairs(head->next->next);
p1->next = head;
head = p1;
}
return head;
}LeetCode之24----Swap Nodes in Pairs
原文:http://blog.csdn.net/jung_zhang/article/details/51211721