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. Set a slow pointer and fast pointer to find the middle of the link
2. Reverse the rear half list.
3. Merge the two list. One by one.
易错点: 注意分开后的两个list 一定要断开连接, slow.next = null !!!! 还有就是 判断循环结束 用 fast.next != null && fast.next.next != null
/**
* 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)
return;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;// The rear half linked list
slow.next = null;
fast = reverseLinkList(fast);//Reverse the list
slow = head;
while(fast != null){
ListNode cur = fast;
fast = fast.next;
cur.next = slow.next;
slow.next = cur;
slow = cur.next;
}
}
private ListNode reverseLinkList(ListNode head){
if(head == null)
return head;
ListNode newHead = new ListNode(0);
while(head != null){
ListNode cur = head;
head = head.next;
cur.next = newHead.next;
//newHead.next = cur.next;
newHead.next = cur;
}
return newHead.next;
}
}