LintCode:重排链表

描述

给定一个单链表L: L0L1→…→Ln-1Ln,

重新排列后为:L0LnL1Ln-1L2Ln-2→…

必须在不改变节点值的情况下进行原地操作。

样例

给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null

挑战

Can you do this in-place without altering the nodes' values?


思路: 首先我们可以想到,可以将链表倒置一下,用linkedlist2代替,

             那么很容易我们就可以达到我们的结果,第一个节点使用第一个链表的,第二个节点使用第二链表的,依次循环下去,

             直到新链表长度跟原链表一样就可以了。

             但是,我们不可以直接将原链表倒置,这样原链表就没了,所以我们先用快慢指针找到中间节点,然后将中间节点后面的

              元素倒置,然后重复上述的过程就可以达到目的了。


Java实现代码如下:

public class reorderList {
    public static void reorderList(ListNode head) {
        // write your code here
        if(head==null || head.next == null){
            return;
        }
        ListNode middle = findMiddle(head);
        ListNode end = reverse(middle);

        ListNode h = head;
        ListNode node1 = null;
        ListNode node2 = null;
        while (h!=null && end!=null){
            node1 = h.next;
            if(node1==middle){
                node1 = null;
            }
            node2 = end.next;
            h.next = end;
            if(node1!=null){
                end.next = node1;
                end = node2;
            }
            h = node1;
        }
    }

    public static ListNode reverse(ListNode middle){
        ListNode pre = null;
        ListNode work = middle;
        ListNode next = middle.next;
        while (next!=null){
            work.next = pre;
            pre = work;
            work = next;
            next = work.next;
        }
        work.next = pre;
        return work;
    }

    public static ListNode findMiddle(ListNode head){
        ListNode h = head;
        while (h!=null && h.next!=null){
            h = h.next.next;
            head = head.next;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/u012156116/article/details/80861332