( Leetcode 24) Swap Nodes in Pairs

来源:互联网 发布:数据分析平台交互设计 编辑:程序博客网 时间:2024/05/16 10:42

题目:Swap Nodes in Pairs

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.


解题思想:

首先应该设置一个空的头结点,为了处理头结点head方便,首先设置一个dummy结点。还有应该都会想到的是设置一个p和q结点,每次这两个交换,但是在交换的时候大家容易忘记的一点就是交换的时候首先假设p在q的前面,我们令 p.next = q.next,这样先删除 了q结点,接下来应该在p结点前面插入q结点,很多人往往直接令q.next = p了,这样做是不对的,因为会导致前面的链表断掉,正确的做法是严格遵守链表插入方法。设置一个pre结点,每次都会记录p结点的前一个结点,然后才能插入q结点。


下面看具体的java代码,应该会明白很多。

public class Solution {    public ListNode swapPairs(ListNode head) {        if( head == null || head.next == null ){        return head;        }        ListNode dummy = new ListNode(-1);        dummy.next = head;        ListNode pre = dummy, p = head, q = head.next;        while( q != null ){        ListNode r = q.next;        p.next = q.next;        q.next = p;        pre.next = q;        //说明到头了,当链表结点个数为偶数个的时候,r == null标明链表到头了//当链表结点个数为奇数个的时候,r.next == null标明链表结点到头了。        if( r == null || r.next == null ){        break;        }        pre = pre.next.next;        p = r;         q = r.next;        }               return dummy.next;    }}

程序运行时间0ms。

0 0
原创粉丝点击