Reorder List

来源:互联网 发布:网络位置可以删除吗 编辑:程序博客网 时间:2024/05/14 09:07

Reorder List

 Total Accepted: 10199 Total Submissions: 51928My Submissions

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}.

Have you been asked this question in an interview? 



public class Solution {
    public void reorderList(ListNode head) {
        //思路:先找到链表的中间节点,用fast和slow指针即可得到,最终的slow为中间指针,把slow后面的链表
        //翻转reverse,然后与head到slow的链表合并即可得到最终给的结果
        
              if(head==null)
 return ;
 ListNode fast;
 Stack<ListNode> stack=new Stack<ListNode>();
     //ListNode preHead=head;
     ListNode afterHead=null;
 ListNode slow=fast=head;
 ListNode q=null;
 while(fast!=null&&fast.next!=null){
 slow=slow.next;
     fast=fast.next.next;
     }
     afterHead=slow.next;
     ListNode p=afterHead;
     slow.next=null;
     while(p!=null){
     stack.push(p);
     p=p.next;
     }
     p=head;
     ListNode temp;
     while(!stack.isEmpty()&&p!=null){
    q=stack.pop();
    q.next=p.next;
    p.next=q;
    p=q.next;   
    }
     //return head;
    }
}
0 0