您的位置:首页 > 其它

Leetcode: Reorder List

2015-06-18 22:22 429 查看


Reorder List

Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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. 两个链表依次重新合并

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {

if(head==null||head.next==null||head.next.next==null)return;

ListNode dummy = new ListNode(0);
dummy.next = head;

ListNode fast = dummy;
ListNode slow = dummy;

while(fast!=null&&fast.next!=null)
{slow = slow.next;fast = fast.next.next;}

ListNode curr = slow.next;
ListNode next = curr.next;
slow.next = null;
curr.next = null;
while(next!=null)
{
ListNode tmp = next.next;
next.next = curr;
curr = next;
next = tmp;
}
ListNode rehead = curr;

ListNode n1 = head;
ListNode n2 = rehead;
int t = 1;

while(n1!=null||n2!=null)
{
if(t==1)
{ListNode tmp = n1.next;n1.next = n2;n1 = tmp;t=2;}
else
{ListNode tmp = n2.next;n2.next = n1;n2 = tmp;t=1;}
}

return;
}
}


 



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息