LeetCode | Swap Nodes in Pairs

来源:互联网 发布:java选择题及答案 编辑:程序博客网 时间:2024/06/06 04:55

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.

于是我们尝试优雅地写代码
一开始是这样的

class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL || head->next==NULL) return head;        ListNode root(-1);        root.next=head;        //三指针        ListNode* pre=&root,*t1=pre->next,*t2=t1->next;        while(t2!=NULL){            //交换            pre->next=t2;            t1->next=t2->next;            t2->next=t1;            //一开始这部分是这样写的            pre=pre->next->next;            if(pre==NULL){                break;            }            else if(pre->next==NULL){                break;            }            else if(pre->next->next==NULL){                break;            }            else{                t1=pre->next;                t2=t1->next;            }            //然后感觉这样写太挫了改成了这样            if(pre!=NULL && pre->next!=NULL && pre->next->next!=NULL){                t1=pre->next;                t2=t1->next;            }            else break;            //嗯...优雅了不少        }        return root.next;    }};

在大神的教导之下,写出了如下代码

//三指针ListNode* pre=&root;while(pre!=NULL && pre->next!=NULL && pre->next->next!=NULL){    //我们只在内部使用到了t1、t2所以只在内部声明它    ListNode* t1=pre->next;    ListNode* t2=pre->next->next;    //交换    pre->next=t2;    t1->next=t2->next;    t2->next=t1;    pre=pre->next->next;}

可以看到,最后一份代码如论是从可读性上和可理解性上来说都比之前好得多。
而如何可以写出如上代码,总结下来,1是经验,2是不要急于敲代码,而是在纸上演算和推理一下,待自己对整个算法有个整体把握之后再写。久而久之,就会成为一种习惯
看了一下答案,它是将整个循环变成一个for循环

for(ListNode* pre=&root;pre!=NULL && pre->next!=NULL && pre->next->next!=NULL;pre=pre->next->next)

可以看到这样更加精炼,所以写代码的时候还是需要多思考

0 0
原创粉丝点击