題目
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.
分析
假設(shè)有連續(xù)的4個節(jié)點A->B->C->D,其中A為已經(jīng)交換過的上一輪的節(jié)點。則一輪交換后為A->C->B->D。運用鏈表的操作方法實現(xiàn)這些節(jié)點關(guān)系的改變即可。
實現(xiàn)
/**
* 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) {
if(head==NULL || head->next==NULL) return head;
ListNode dummy(-1);
ListNode *p=&dummy, *tmp;
dummy.next = head;
while(p!=NULL && p->next!=NULL && p->next->next!=NULL){
tmp = p->next->next;
p->next->next = tmp->next;
tmp->next = p->next;
p->next = tmp;
p = p->next->next;
}
return dummy.next;
}
};
思考
對于這題來說,使用三個指針代碼會簡潔一些。