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.
此题要点:
1. 添加伪头结点,便于处理头结点
2. p2是否为空指针的判断
/**
* 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) {
ListNode *pseudo = new ListNode(0);
pseudo->next = head;
ListNode *p1 = pseudo;
ListNode *p2 = head;
//exchange p1->next and p2->next
while(p2 && p2->next){
p1->next = p1->next->next;
p2->next = p1->next->next;
p1->next->next = p2;
if(p1->next->next) p1 = p1->next->next;
if(p2->next) p2 = p2->next;
}
return pseudo->next;
}
};