您的位置:首页 > Web前端 > Node.js

【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素

2016-08-06 13:37 661 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if (head==NULL||head->next==NULL){
return head;
}
struct ListNode *p,*t;
struct ListNode *newHead=head->next;
struct ListNode *tail=NULL;
while (head){
if (head->next==NULL){
tail->next=head;
return newHead;
}
p=head->next;
if (tail!=NULL){
tail->next=p;
}
t=p->next;
p->next=head;
tail=head;
head=t;
}
tail->next=NULL;
return newHead;
}


题不是很难,但是相对其他题想了蛮久,因为指针有点多,绕来绕去就绕晕了。

用了四个指针,head(原链表的头),tail(新链表的尾),p(新链表的头),t(下一次循环要用到的原链表的头)。


搞清楚每次循环的开始做什么和结束做什么是关键

开始的时候:将上次反转后的链表的tail指向新链表的头p;


结束的时候:更新tail,head
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表 交换