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

LeetCode(143): Recorder List

时间:2016-01-18 20:46:09      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

Recorder List: Given a singly linked list L: L0L1→…→Ln-1Ln,reorder it to: L0LnL1Ln-1L2Ln-2→…You must do this in-place without altering the nodes‘ values.For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

题意:给定一个链表,把最后一个结点插入到第一个结点后面,倒数第二个结点插入到原链表第二个结点后面,依次类推。

思路:利用快慢指针的方法找到链表的中点,然后逆转中点右边的链表,然后将两个链表合并。

代码:

public void reorderList(ListNode head) {
        if(head == null || head.next == null) return;

        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode mid = slow.next;
        ListNode cur = mid;
        ListNode pre = null;
        while(cur != null){
            ListNode post = cur.next;
            cur.next = pre;
            pre = last;
            cur = post;
        }
        slow.next = null;

        while(head != null && pre != null){
            ListNode next1 = head.next;
            head.next = pre;
            pre = pre.next;
            head.next.next = next1;
            head = next1;
        }
        
    }

LeetCode(143): Recorder List

标签:

原文地址:http://www.cnblogs.com/Lewisr/p/5140237.html

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