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}.
一刷
题解:
先将median的之后的节点reverse, 然后再逐一连起来
/**
* 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) return;
ListNode p1 = head;
ListNode p2 = head;
while(p2.next!=null && p2.next.next!=null){
p1 = p1.next;
p2 = p2.next.next;
}
//then p1 indicate the medium
//reverse after the medium
// 1->2->3->4->5->6 to 1->2->3->6->5->4
ListNode preMid = p1;
ListNode preCur = p1.next;
//preMid.next indicate the head, cur connect with the preMid.next
while(preCur.next!=null){
ListNode cur = preCur.next;
preCur.next = cur.next;
cur.next = preMid.next;//connect the head
preMid.next = cur;//change the head
}
p1 = head;
p2 = preMid.next;
while(p1!=preMid){
preMid.next = p2.next;//change the head
p2.next = p1.next;
p1.next = p2;
p1 = p2.next;
p2 = preMid.next;
}
}
}
二刷
思路同一刷
不过要注意快慢指针的停止位置: while(fast.next!=null && fas t.next.next!=null)
这样保证从slow的后面开始reverse
/**
* 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) {
//first reverse half and linked each other from the both head
//find the medium
if(head == null || head.next==null) return;
ListNode fast = head, slow = head;
while(fast.next!=null && fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
}
//reverse after the medium
ListNode prev = null, cur = slow.next;
while(cur!=null){
ListNode next = cur.next;
cur.next = prev;
slow.next = cur;
prev = cur;
cur = next;
}
ListNode first = head, second = slow.next;
slow.next = null;
while(first!=null && second!=null){
ListNode fNext = first.next;
ListNode sNext = second.next;
first.next = second;
second.next = fNext;
first = fNext;
second = sNext;
}
}
}