码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Swap Nodes in Pairs

时间:2015-11-14 06:18:00      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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.


解题思路:

需要运用fakehead来指向原指针头,防止丢链,用两个指针,pre始终指向需要交换的pair的前面一个node,cur始终指向需要交换的pair的第一个node。

然后就进行正常的链表交换,和指针挪动就好。 

当链表长度为奇数时,cur.next可能为null;

当链表长度为偶数时,  cur可能为null。

所以把这两个情况作为终止条件,在while判断就好,最后返回fakehead.next。

链表交换死活看不懂,需要人帮我讲下。


Java code:

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        
        ListNode pre = fakehead;
        ListNode cur = head;
        
        while(cur!= null && cur.next != null) {
           pre.next = cur.next;
           cur.next = cur.next.next;
           pre.next.next = cur;
           pre = cur;
           cur = cur.next;
        }
        return fakehead.next;
    }
}

Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-swap-nodes-in-pairs.html

2. http://www.cnblogs.com/springfor/p/3862030.html

 

Leetcode Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4963680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!