LeetCode143之ReorderList的Java题解

题目:

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

解答:

一看到这题我一开始联想到对链表进行排序那题,同样可以分为三个步骤:

1,寻找链表的中间节点(快慢指针)

2,对链表进行倒置

3,节点插入

代码如下:

public static void reorderList(ListNode head) {
		if(head!=null&&head.next!=null)
		{
		ListNode middle=getMideeldofList(head);
		ListNode next=middle.next;
		middle.next=null;
		ListNode backNode=ReverseList(next);
		ListNode cur=head,cur1=backNode;
		ListNode next1=null,next2=null;
		while(cur!=null&&cur1!=null)
		{
			 next1=cur.next;
			 next2=cur1.next;
			 cur.next=cur1;
			 cur1.next=next1;
			 cur=next1;
			 cur1=next2;
		}
		}
		
		
		
        
    }
	public static ListNode getMideeldofList(ListNode head)
	{
		if(head==null||head.next==null)
			return head;
		ListNode slow=head,fast=head;
		while(fast!=null&&fast.next!=null)
		{
			fast=fast.next.next;
			slow=slow.next;
			
		}
		return slow;
	}
	public static ListNode ReverseList(ListNode head)
	{
		if(head==null||head.next==null)
			return head;
		ListNode fakeNode=new ListNode(-1);
		fakeNode.next=head;
		ListNode pre=fakeNode,cur=head.next,firstNode=head;
		while(cur!=null)
		{
			ListNode next=cur.next;
			cur.next=pre.next;
			pre.next=cur;
			cur=next;
		}
		firstNode.next=null;
		return fakeNode.next;
	}

第二种解法:

听过一句话,软件解决起来很复杂的问题有时候用硬件能够很轻松地解决,同样需要用复杂的代码实现的功能有时候通过选择恰当的数据结构能够很方便解决。

在这题中,我们可以通过把链表的节点放入一个栈中,通过这么一个步骤可以实现上面寻找中间节点和链表转置两个功能,接着就只需要进行节点插入的操作了。

代码:

public static void reorderList2(ListNode head) {
		  if(head==null||head.next==null)
			  return;
		  Stack<ListNode> stack=new Stack<>();
		  ListNode cur=head;
		  while(cur!=null)
		  {
			  stack.push(cur);
			  cur=cur.next;
		  }
		  int count=stack.size()/2;
		  cur=head;
		  ListNode nextNode=null,tempNode=null;
		  while(count>0)
		  {
			  tempNode=stack.pop();
			  nextNode=cur.next;
			  cur.next=tempNode;
			  tempNode.next=nextNode;
			  cur=nextNode;
			  count--;
			  
		  }
		  if(nextNode!=null)
		  {
			  nextNode.next=null;
		  }
		  
		  
		  
	  }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值