leetcode--Reorder List

来源:互联网 发布:数据洪流 编辑:程序博客网 时间:2024/05/16 10:50

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

[java] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public void reorderList(ListNode head) {  
  11.         if(head==null||head.next == nullreturn;  
  12.         ListNode slow = head;  
  13.         ListNode fast = head;  
  14.         while(slow!=null&&fast!=null&&fast.next!=null){  
  15.             slow = slow.next;  
  16.             fast = fast.next.next;  
  17.         }  
  18.         ListNode mid = slow.next;  
  19.         ListNode last = mid;  
  20.         ListNode pre = null;  
  21.         while(last!=null){  
  22.             ListNode t = last.next;  
  23.             last.next = pre;  
  24.             pre = last;  
  25.             last = t;  
  26.         }  
  27.         slow.next = null;         
  28.         while(head!=null&&pre!=null){             
  29.             ListNode t = head.next;  
  30.             head.next = pre;  
  31.             pre = pre.next;  
  32.             head.next.next = t;  
  33.             head = t;  
  34.         }  
  35.     }  
  36. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46564187

原创粉丝点击