24. Swap Nodes in Pairs

来源:互联网 发布:java标识符是什么 编辑:程序博客网 时间:2024/06/08 16:30

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.

Subscribe to see which companies asked this question

题目要求每两个数之间交换一下。

感觉自己在链表这一块确实很薄弱,每次写都会遇到很多问题,真的是很不熟练。
自己这个题目思路不清晰,写的代码太凌乱了。
学习了别人的代码:http://blog.csdn.net/feliciafay/article/details/17573327

递归代码:

class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL||head->next==NULL)            return head;        ListNode *q=head->next;        head->next=q->next;        q->next=head;        q->next->next=swapPairs(q->next->next);        return q;    }};

非递归的:

class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL||head->next==NULL)            return head;        ListNode *p=head;        ListNode *q=head->next;        ListNode *x=head->next->next;        ListNode *t=NULL;        head=q;        while(p!=NULL&&q!=NULL){            p->next=NULL;             q->next=p;            if(t!=NULL)                t->next=q;            t=p;            p=x;            if(x!=NULL)q=x->next;            if(q!=NULL)x=q->next;        }        if(p!=NULL)            t->next=p;        return head;    }};
0 0
原创粉丝点击