新博文地址:[leetcode]Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: 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 to {1,4,2,3}.
reorder it to: 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 to {1,4,2,3}.
算法思路:
设置快慢指针将前半段与后半段分开,然后将后半段逆序,再逐个插入前半段,时间复杂度O(n),空间复杂度不定
思路1:
后半段的逆序,设置三指针,在原list基础上逆序,空间复杂度O(1)
后面还有一些题会用这个思路,这里就不实现了。
代码如下:
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return ;
ListNode hhead = new ListNode(0);
hhead.next = head;
ListNode fast = hhead;
ListNode slow = hhead;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode stackPart = slow.next;
slow.next = null;
Stack<ListNode> stack = new Stack<ListNode>();
while(stackPart != null){
stack.push(stackPart);
stackPart = stackPart.next;
}
ListNode insert = head;
while(!stack.isEmpty()){
ListNode tem = stack.pop();
tem.next = insert.next;
insert.next = tem;
insert = tem.next;
}
}
}