24. 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.

http://www.jianshu.com/p/6b64490cac79 的简单版本when k =2

Solution1:Recursive: 先序处理

思路:发现pattern子问题,处理好当前的,递归剩下的
Time Complexity: O(N) Space Complexity: O(N) 递归缓存

屏幕快照 2017-09-11 下午12.51.38.png

Solution2:Iterative

思路:遍历每次处理一个section(两个nodes)
Time Complexity: O(N) Space Complexity: O(1)

屏幕快照 2017-09-11 下午1.07.26.png

Solution2.2 Round1:Iterative

Solution1 Code:

class Solution1 {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        
        ListNode second = head.next;
        
        head.next = swapPairs(second.next);
        second.next = head;
        return second;
    }
}

Solution2 Code:

class Solution2 {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode current = dummy;
        while (current.next != null && current.next.next != null) {
            ListNode first = current.next;
            ListNode second = current.next.next;
            
            first.next = second.next;
            second.next = first;
            current.next = second;
            
            current = current.next.next;
        }
        return dummy.next;
    }
}

Solution2.2 Round1 Code:

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode cur = dummy;
        
        while(cur != null) {
            cur = swapPair(cur);
        }
        
        return dummy.next;
    }
    
    private ListNode swapPair(ListNode pre) {
        if(pre.next == null || pre.next.next == null) {
            return null;
        }
        ListNode cur = pre.next;
        ListNode post = cur.next;
        ListNode save = post.next;
        
        pre.next = post;
        post.next = cur;
        cur.next = save;
        
        return cur;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • Given a linked list, swap every two adjacent nodes and re...
    番茄晓蛋阅读 133评论 0 0
  • 我听见风吹动窗帘,却没有发现自己隐身于黑暗。或许有太多遇见都不是出于自愿。所以宁愿,一个人承受。不分享出那些离合...
    随风渐渐阅读 300评论 0 1
  • 我与“孙悟空”的渊源 孙悟空在中国是一个家喻户晓的人物。最近这几年关于孙悟空的影视作品有很多。而只要是口碑还不错的...
    吴宇仁阅读 836评论 1 4
  • 作者:查尔斯·布考斯基 翻译:刘淼 1969年,黑麻雀出版社的约翰·马丁向49岁的布考斯基提出,从此以后每个月给...
    刘淼阅读 2,295评论 7 63