1. 程式人生 > >Leetcode 143.重排鏈表

Leetcode 143.重排鏈表

示例 listnode 需要 != amp next pub == ()

重排鏈表

給定一個單鏈表 LL0L1→…→Ln-1Ln ,
將其重新排列後變為: L0LnL1Ln-1L2Ln-2→…

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

示例 1:

給定鏈表 1->2->3->4, 重新排列為 1->4->2->3.

示例 2:

給定鏈表 1->2->3->4->5, 重新排列為 1->5->2->4->3.

 1 public class Solution{
 2     public void reorderList(ListNode head){
3 if(head==null) return; 4 ListNode slow=head,fast=head; 5 while(fast!=null && fast.next!=null){ 6 slow=slow.next; 7 fast=fast.next.next; 8 } 9 Stack<ListNode> stack=new Stack<>(); 10 ListNode half=slow.next;
11 while(half!=null){ 12 stack.push(half); 13 half=half.next; 14 } 15 slow.next=null; 16 ListNode current=head; 17 while(current!=null && !stack.isEmpty()){ 18 ListNode next=current.next; 19 current.next=stack.pop();
20 current.next.next=next; 21 current=next; 22 } 23 } 24 }

Leetcode 143.重排鏈表