Reorder list
Given a singly linked listL:L0 →L1 →... →LN-1 →LN,
Reorder it:L0 →LN→L1 →LN-1 →L2 →LN-2 →...
You must do this in-place without altering the nodes 'values.
For example,
Given{1,2,3,4}, Reorder it{1,4,2,3}.
Algorithm ideas:
Set the speed pointer to separate the first half and the second half, then sort the second half in reverse order, and insert the first half one by one. The time complexity is O (n), and the space complexity is variable.
Thought 1:
In reverse order of the second half, set three pointers to reverse order based on the original list, space complexity O (1)
There are still some questions that will be used here, so this will not be implemented here.
Idea 2:
The reverse order of the second half. With stack and space complexity O (n), the code is simple.
The Code is as follows:
1 public class Solution { 2 public void reorderList(ListNode head) { 3 if(head == null || head.next == null) return ; 4 ListNode hhead = new ListNode(0); 5 hhead.next = head; 6 ListNode fast = hhead; 7 ListNode slow = hhead; 8 while(fast != null && fast.next != null){ 9 fast = fast.next.next;10 slow = slow.next;11 }12 ListNode stackPart = slow.next;13 slow.next = null;14 Stack<ListNode> stack = new Stack<ListNode>();15 while(stackPart != null){16 stack.push(stackPart);17 stackPart = stackPart.next;18 }19 ListNode insert = head;20 while(!stack.isEmpty()){21 ListNode tem = stack.pop();22 tem.next = insert.next;23 insert.next = tem;24 insert = tem.next;25 }26 }27 }