您的位置:首页 > 其它

LeetCode之 Reorder List解决思路

2014-06-23 14:37 465 查看
题目如下:

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) +1, 第二部分取剩余的。 分割后的两个链表都要将末尾置为NULL。

这种分割方法,需要先遍历链表长度,再进行分割,需要遍历两次链表。因此可以改进成采用快慢节点取得中间节点的方式,只要一遍遍历即可。

(2)反转链表的第二部分

(3)合并链表的两部分

/**
* 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 || head.next.next == null) return;
ListNode Head = split(head);
merge(head, Head);

}

private int length(ListNode head){
int len = 0;
ListNode p = head;
while(p != null){
len++;
p = p.next;
}
return len;
}

private ListNode split(ListNode head, int len){
int splitPos = (len / 2) + 1;
ListNode p = head;
splitPos--;
while(splitPos != 0){
p = p.next;
splitPos--;
}
ListNode Head = p.next;
p.next = null;
return reverse(Head);
}

private ListNode split(ListNode head){
ListNode slow = head;
ListNode fast = slow.next;
while(fast.next != null && fast.next.next != null)

slow = slow.next;
fast = fast.next.next;
}
slow = slow.next;
ListNode Head = slow.next;
slow.next = null;
return reverse(Head);
}

private ListNode reverse(ListNode p){
if(p == null || p.next == null) return p;
ListNode current = p.next;
p.next = null;
while(current != null){
ListNode temp = current;
current = current.next;
temp.next = p;
p = temp;
}
return p;
}

private void merge(ListNode p, ListNode q){
ListNode current = p;
while(q != null){
ListNode temp = q;
q = q.next;
temp.next = current.next;
current.next = temp;
current = current.next.next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Reorder List