题目:iven 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.
交换链表每两个元素的位置。
思路:
1.出现单个的情况链表不变
2.链表为空或者只有一个元素,返回head头指针即可。
3.需要一个p保存开始的头指针,在不为空时p=head->next。最后返回p->next。
3.需要一个pre指针指向每次交换完成后最后的那个node。移动head,交换完成后将pre指向head->next。
具体见图。解释了while(head->next)和if(q->next)时的情况每一步做了什么。
/**
* 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* p=new ListNode(0);
p->next=head->next;
ListNode* pre=p;
ListNode* q=head->next;
while(head->next){
q=head->next;
if(q->next){
head->next=q->next;
q->next=head;
head=head->next;
pre->next=q;
pre=q->next;
}
else{
head->next=NULL;
q->next=head;
pre->next=q;
}
}
return p->next;
}
};
4ms AC。