重排链表

 给定一个单链表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; 
	  }
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值