Special rotating LeetCode-place algorithm singly linked list

Problem Description:

Given a single linked list L: L 0 → L 1 → ... → L n-1 → L n,
Reorder: L 0 → L n → L 1 → L n-1 → L 2 → L n-2 → ...
It requires the use of in-place algorithm, and does not change the value of the node
E.g:
For a given single chain {1,2,3,4}, which is {1,4,2,3} reordered.
Given a singly linked list L: L 0→L 1→…→L n-1→L n,

reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.

 

Problem-solving ideas: to consider the original list split into two, the pointer can be found using the speed of the intermediate node list

    Then inverted to achieve the latter part of the list, using the in-place algorithm

    And then combined into a single list two lists of achieving these requirements

Copy the code
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    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;
        slow.next = null;
        ListNode after = getReverse(mid);
        getAdd(head, after);
    }
    public ListNode getReverse(ListNode node){
        ListNode pre = null;
        while(node != null){
            ListNode temp = node.next;
            node.next = pre;
            pre = node;
            node = temp;
        }
        return pre;
    }
    public void getAdd(ListNode node1,ListNode node2){
        while(node1 != null && node2 !=null){
            ListNode f = node1.next;
            ListNode a = node2.next;
            node1.next = node2;
            node1 = f;
            node2.next = node1;        
            node2 = a;
        }
    }
}

Guess you like

Origin www.cnblogs.com/lc1475373861/p/12026956.html