算法系列——Swap Nodes in Pairs

来源:互联网 发布:怎么在淘宝上拿货的 编辑:程序博客网 时间:2024/06/05 02:45

题目描述

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.

解题思路

这个题目稍微复杂一点。如下图所示,我们引入虚拟头结点,并且利用4个指针p,node1,node2,next,分别表示 描述 前驱,交换结点1,交换结点2和后继。更新这四个结点的值即可。

这里写图片描述

程序实现

public class Solution {    public ListNode swapPairs(ListNode head) {        if(head==null)            return null;        ListNode dummyHead=new ListNode(-1);        dummyHead.next=head;        ListNode p=dummyHead;        while(p.next!=null&&p.next.next!=null){            ListNode node1=p.next;            ListNode node2=p.next.next;            ListNode next=node2.next;            node2.next=node1;            node1.next=next;            p.next=node2;            p=node1;        }        return dummyHead.next;    }}
原创粉丝点击