Reorder List

https://leetcode.com/problems/reorder-list/
给定一个链表,按特定的规则对链表进行插入翻转
L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

  • 思路
    类似于用归并法链表排序的思路~
    将链表从中间分成两份,将后部分翻转~
    然后将后部分逐个插入到前部分中
public void reorderList(ListNode head) {
        if(head == null){
            return;
        }
        ListNode fast = head;
        ListNode slow = head;

        //把ListNode一切为二,从中间拨开
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode firstNode = head;
        ListNode secondNode = slow.next;
        slow.next = null;

        //后半段的ListNode翻转
        ListNode secondRNode = reverseNode(secondNode);

        //后半段的ListNode插入到前半段的ListNode中
        while (firstNode != null && secondRNode != null) {
            ListNode tmp1 = firstNode.next;
            ListNode tmp2 = secondRNode.next;
            firstNode.next = secondRNode;
            secondRNode.next = tmp1;
            secondRNode = tmp2;
            firstNode = firstNode.next.next;
        }
    }

    public ListNode reverseNode(ListNode list) {
        if(list == null){
            return null;
        }
        ListNode slow = null;
        ListNode fast = null;
        while (list.next != null) {
            fast = list.next;
            list.next = slow;
            slow = list;
            list = fast;
        }
        list.next = slow;
        return list;
    }

你可能感兴趣的:(Reorder List)