Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}.

 

思路: 利用slow和fast指针找到中间节点 slow指向 n/2 + 1个位置, fast指向尾部节点(奇数)或者null(偶数)

其次利用reverse,返回链表,即出入head之前,并变换head的指针

java代码:

  1. public void reorderList(ListNode head) {
  2. ListNode p = head;
  3. ListNode slow=head;
  4. ListNode fast = head;
  5. if(head==null || head.next==null) return;
  6. while(fast!=null && fast.next!=null) {  //slow指针
  7. slow=slow.next;
  8. fast=fast.next.next;
  9. }
  10. fast=slow.next;
  11. slow.next=null;
  12. if(fast==null) return;
  13. p=fast.next;
  14. fast.next=null;  //消除新链表的尾部
  15. while(p!=null){  //reverse
  16. ListNode tmp=p.next;
  17. p.next=fast;
  18. fast=p;
  19. p=tmp;
  20. }
  21. p=head;
  22. while(fast!=null) {  //merge
  23. ListNode tmp=fast.next;
  24. fast.next=p.next;
  25. p.next=fast;
  26. p=p.next.next;
  27. fast=tmp;
  28. }
  29. // return head;
  30. }

 

posted @ 2014-07-26 11:56  purejade  阅读(78)  评论(0)    收藏  举报