首页 > 其他 > 详细

[LintCode] Reorder List

时间:2015-11-17 12:47:54      阅读:294      评论:0      收藏:0      [点我收藏+]

Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes‘ values.

Example

For example,
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

 
SOLUTION:
怎么才能满足这样的排序呢?很简单,先二分,把它分成两个链表,再翻转后面的链表,再合并两个链表。单个功能的实现,前面都有了就不赘述了。
 
代码:
技术分享
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */
    public void reorderList(ListNode head) {  
        if (head == null || head.next == null){
            return;
        }
        ListNode mid = findMid(head);
        ListNode node = mid.next;
        mid.next = null;
        node = reverse(node);
        head = merge(head, node);
    }
    private ListNode findMid(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private ListNode reverse(ListNode head){
        if (head == null){
            return head;
        }
        ListNode prev = null;
        while (head != null){//错误的地方
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
    private ListNode merge(ListNode l1, ListNode l2){
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (l1 != null && l2 != null){
            head.next = l1;
            head = l1;
            l1 = l1.next;
            head.next = l2;
            head = l2;
            l2 = l2.next;
        }
        if (l1 != null){
            head.next = l1;
        }
        if (l2 != null){
            head.next = l2;
        }
        return dummy.next;
    }
}
View Code

 

[LintCode] Reorder List

原文:http://www.cnblogs.com/tritritri/p/4971175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!