重排链表

来源:互联网 发布:欧美电影推荐知乎 编辑:程序博客网 时间:2024/06/07 06:27
 给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
样例

给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。

import java.util.Scanner;import java.util.Stack;/** * 给定一个单链表L: L0→L1→…→Ln-1→Ln,重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…必须在不改变节点值的情况下进行原地操作。样例给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。 *  * @author Dell * */public class Test99 {  public static void reorderList(ListNode head)  {  if(head==null||head.next==null)  return;  ListNode temp=new ListNode(-1);  temp.next=head;  ListNode mid=find(temp);  ListNode later=mid.next;  mid.next=null;  Stack<ListNode> s=new Stack<>();  while(later!=null)  {  ListNode t=later;  later=later.next;  s.push(t);  }  ListNode p=temp.next;  ListNode q=null;  while(s.isEmpty()!=true&&p!=null)  {  q=p;  p=p.next;  ListNode zz=s.pop();  q.next=zz;  zz.next=p;    }    }  public static ListNode find(ListNode head)  {  ListNode slow=head.next;  ListNode fast=head.next;  while(fast.next!=null&&fast.next.next!=null)  {  slow=slow.next;  fast=fast.next.next;    }  return slow;  }public static void main(String[] args) {Scanner sc=new Scanner(System.in);int n=sc.nextInt();ListNode head=new ListNode(-1);ListNode p=head;  for(int i=0;i<n;i++)   { ListNode temp=new ListNode(sc.nextInt()); p.next=temp; p=p.next;   }  reorderList(head.next);  ListNode q=head.next;  while(q!=null)  {  System.out.print(q.val+" ");  q=q.next;   }}}


原创粉丝点击