Swap Nodes in Pairs

来源:互联网 发布:外汇ea编程 编辑:程序博客网 时间:2024/05/13 05:30

题目:Given a linked list, swap every two adjacent nodes and return its head.

Given 1->2->3->4

you should return the list as 2->1->4->3.

思路:设立tail作为下一个list前一个结点,所以每次判断当前和之后是否为空

    看了一下思路,立即ACCEPTED。

本题思路很多,但是方法的不同,会导致解决的难易程度。我在一开怎么都不会accepted,原因就是个别情况不能考虑。

设立tail作为下一个list前一个结点,所以每次判断当前和之后是否为空。这是一大技巧,还有就是每次都是判断

“head!=NULL&&head->next!=NULL”,并且设立一个暂时的tmp,迭代来讲,head指向head->next->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 *dummy=new ListNode(-1);        ListNode *tail=dummy;                while(head!=NULL&&head->next!=NULL){            ListNode *tmp=head->next;            head->next=tmp->next;            tail->next=tmp;            tmp->next=head;                        tail=head;head=head->next;                    }        head=dummy->next;        delete dummy;                return head;    }};



0 0
原创粉丝点击