题目描述
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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->3->4->5->6
将p设定为head,也就是1,q设定为2,r设定为3,他们的关系就是:
p=head;
q=head->next;
r=q->next;
然后将p->next指向r,q->next指向p,完成了p,q之间的调换,
p->next=r;
q->next=p;
接着移动p, q, r到下一个节点:
p=r;
q=r->next;
r=r->next->next;
再进行上述重复的调换,直到p或q为NULL,表示到最后了。
接下来贴出代码:
/**
* 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* res = new ListNode(0);
res->next=head;
ListNode* tmp=res;
ListNode* p=head;
ListNode* q=head->next;
ListNode* r=q->next;
while(q!=NULL && p!=NULL){
q->next=p;
p->next=r;
tmp->next=q;
tmp=p;
p=r;
q=r->next;
r=r->next->next;
}
return res->next;
}
};
这里用了一个辅助指针作为表头,也就是res->next,这是链表中常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
ListNode* res = new ListNode(0);
res->next = head;
然后新建一个tmp节点,让其等于res,然后让这个tmp节点随着处理而变化,比如循环中第一个tmp->next=q, 也就是将q节点,放在头节点,也就是res->next,紧接着tmp=p,也就是将tmp节点移动到p,而p是q的下一个,也就相当于交换了p和q的位置。