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

24. Swap Nodes in Pairs -leetcode-java

2016-05-26 18:54 609 查看
今天一下午被这道题困惑好久,也是够笨呀。

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
.
题意就是交换一个链表每两个相邻节点。
public class Solution {

    public ListNode swapPairs(ListNode head) {

        if(head==null || head.next==null) return head;

       // ListNode fakehead=null;

       ListNode fakehead=new ListNode(-1);//注意这里要初始化赋值,-1这个数是任意的哈

        fakehead.next=head;

        ListNode ptr1=fakehead;

        ListNode ptr2=head;

        ListNode nextstart;

        while(ptr2!=null && ptr2.next!=null){

            nextstart=ptr2.next.next;

            ptr2.next.next=ptr2;//对应图的第二步

            ptr1.next=ptr2.next;//对应图的第三步

            ptr2.next=nextstart;//对应图的第四步

            ptr1=ptr2;//上面交换完成了,这里指针开始挪动到下一位置了

            ptr2=ptr2.next;//指针挪动

        }

        return fakehead.next;

    }

}

画了下图……

交换过程:



注意ptr1 ptr2就是两个指针,指针本次任务完成了,就接着移动,该指向下一轮啦。整个链表的头结点的使命,交给fakehead。也就是fakehead.next也就是常说的dummy。用这个假节点,next指向头结点,以便于保持和后续的节点处理一致。方便操作。

参考资料:

博客园-Swap Nodes in Pairs 


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: