您的位置:首页 > 其它

Leetcode: Reorder List

2014-10-25 08:10 316 查看
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. count the length of the linked list to find the node at the middle
2. Reverse the list from the middle node to the end, and let middle node point to null, to let the list start from tail and lead to middle

3. Merge the part before and after the middle node in required order

/**
* 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 dummyHead = new ListNode(0);
dummyHead.next = head;

int length = listLength(head);
for (int i = 0; i < length / 2; i++) {
head = head.next;
}

ListNode mid = head;
ListNode p1 = head.next;
while (head != null && p1 != null) {
ListNode p2 = p1.next;
p1.next = head;
head = p1;
p1 = p2;
}
mid.next = null;

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

head = dummyHead.next;
while (head != null && head.next != null && dummyTail.next != null && dummyTail.next != head.next) {
ListNode nextHead = head.next;
ListNode nextTail = dummyTail.next;
dummyTail.next = nextTail.next;
head.next = nextTail;
nextTail.next = nextHead;
head = nextHead;
}

head = dummyHead.next;
}

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

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