url :
https://leetcode.com/problems/reorder-list/description/
描述
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}.
代码
class Solution {
public void reorderList(ListNode head) {
if(head == null) return;
ListNode p = head;
int count = 0;
while(p!=null){
p=p.next;
count++;
}
ListNode[] points = new ListNode[count];
p = head;
count = 0;
while(p!=null){
points[count++] = p;
p=p.next;
}
int i = 0, j = count-1;
while(i < j) {
points[i].next = points[j];
points[j--].next = points[++i];
}
points[i].next = null;
}
}
上面的方法总是感觉有点不正宗,下面给出链表的操作,大概就是把链表的后半段作为单独的一段链表,并进行反转,然后在把两个合成一个就行啦,代码如下:
public void reorderList3(ListNode head) {
if(head==null) return;
ListNode fast = head, slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
if(fast!=null){
slow = slow.next;
}
}
ListNode pre = null;
ListNode p = slow.next;
ListNode post = p==null ? null : p.next;
while(post!=null){
p.next = pre;
pre = p;
p=post;
post = post.next;
}
if(p!=null)
p.next = pre;
slow.next = null;
ListNode h1 = head;
ListNode h2 = head.next;
ListNode m = p;
while(h1!=null && m!=null) {
h1.next = m;
m = m.next;
h1 = h1.next;
h1.next = h2;
h2 = h2 == null? null : h2.next;
h1 = h1.next;
}
}