1 题目
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
2 尝试解
/**
* 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* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre;
ListNode* cur = dummy;
while((pre=cur) && (cur = pre->next)&&(cur->next!=NULL)){ //for example, 0->1->2->3, swap 1 and 2, pre = 0, cur = 1
pre->next = cur->next; //0->2->3 1->2->3
cur->next = cur->next->next; //0->2->3 1->3
pre->next->next = cur; // 0->2->1->3
}
return dummy->next;
};
};
3 标准解
ListNode* swapPairs(ListNode* head) {
ListNode **pp = &head, *a, *b;
while ((a = *pp) && (b = a->next)) {
a->next = b->next;
b->next = a;
*pp = b;
pp = &(a->next);
}
return head;
}