码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 143.重排链表

时间:2018-12-29 15:17:17      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:strong   solution   ack   empty   while   void   stack   next   code   

重排链表

给定一个单链表 LL0L1→…→Ln-1Ln ,
将其重新排列后变为: L0LnL1Ln-1L2Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

 

 1 public class Solution{
 2     public void reorderList(ListNode head){
 3         if(head==null) return;
 4         ListNode slow=head,fast=head;
 5         while(fast!=null && fast.next!=null){
 6             slow=slow.next;
 7             fast=fast.next.next;
 8         }
 9         Stack<ListNode> stack=new Stack<>();
10         ListNode half=slow.next;
11         while(half!=null){
12             stack.push(half);
13             half=half.next;
14         }
15         slow.next=null;
16         ListNode current=head;
17         while(current!=null && !stack.isEmpty()){
18             ListNode next=current.next;
19             current.next=stack.pop();
20             current.next.next=next;
21             current=next;
22         }
23     }
24 }

 

Leetcode 143.重排链表

标签:strong   solution   ack   empty   while   void   stack   next   code   

原文地址:https://www.cnblogs.com/kexinxin/p/10195954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!