题目
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.
分析
假设有连续的4个节点A->B->C->D,其中A为已经交换过的上一轮的节点。则一轮交换后为A->C->B->D。运用链表的操作方法实现这些节点关系的改变即可。
实现
/**
* 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;
}
};
思考
对于这题来说,使用三个指针代码会简洁一些。