leetcode:Reorder List

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

题目分析:

这是一个链表重排序问题,其实只要能够做到链表倒序,然后一个个插进去就可以了,这样时间,空间复杂度都为o(n)

代码如下:

 

  public static void reorderList(ListNode head) {
		  ListNode p=head;
		  int len=getlength(head);
		  if(len<=1) return ;
		  ListNode q=head;
		  ListNode newhead=null;
		  ListNode index=null;
		  while(q!=null)
		  {
			  ListNode x=new ListNode(q.val);
			  if(newhead==null)
			  {
				  newhead=x;
				  index=newhead;
			  }
			  else
			  {
				 x.next=index;
				index=x;
				newhead=x;
			  }
			  q=q.next;
		  }
		  ListNode m=head;
		  ListNode n=newhead;
		  if((len%2)==1)
		  {
		     for(int i=0;i<len/2;i++)
		     {
			  ListNode tmp1=n.next;
			  ListNode tmp2=m.next;
			  n.next=tmp2;
			  m.next=n;
			  n=tmp1;
			  m=tmp2;
		     }
		     m.next=null;
		  }
		  else
		  {
			  for(int i=0;i<len/2-1;i++)
			  {
				  ListNode tmp1=n.next;
				  ListNode tmp2=m.next;
				  n.next=tmp2;
				  m.next=n;
				  n=tmp1;
				  m=tmp2;
			   }
			  m.next=n;
			  n.next=null;
		  }
		  
	        
	    }
	  
	  public static int getlength(ListNode head)
	  {
		  int num=0;
		  ListNode p=head;
		  while(p!=null)
		  {
			  num++;
			  p=p.next;
		  }
		  return num;
	  }
	  

 

需要注意的地方为:1:链表处理要注意指向,不要出现死循环 2:奇数个和偶数个处理方式略有不同,注意区分

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值