您的位置:首页 > 其它

leetcode 之 Reorder List

2014-04-22 15:52 295 查看
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.

思路:首先找到链表的中间节点,从中间断开链表,得到l1,l2;反转链表l2,然后顺序的将l2的节点插入到l1中;每隔一个节点插入一个。

源代码如下:

/**
* Definition for singly-linked list.
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null)
return ;
ListNode pslow = head, pfast = head;
while(pfast != null && pfast.next != null){
pslow = pslow.next;
pfast = pfast.next.next;
}

ListNode midNode = pslow.next;
pslow.next = null;
ListNode secondNode = reverse(midNode);
pslow = head;
pfast = secondNode;
while(pslow.next != null && pfast != null)
{
midNode = pfast;
pfast = pfast.next;
midNode.next = pslow.next;
pslow.next = midNode;
pslow = pslow.next.next;
}
if(pslow.next == null)
pslow.next = pfast;
}
ListNode reverse(ListNode head){
if(head == null || head.next == null)
return head;
ListNode current = head.next;
head.next = null;
while(current != null)
{
ListNode tmpNode = current;
current = current.next;
tmpNode.next = head;
head = tmpNode;

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