前言
本週刷題未鏈表排序相關知識點
題目
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
解題思路
- 首先利用快慢指針找到中間節點
- 從中間節點截斷鏈表,並將中間節點之後得鏈表進行反轉操作
- 同時遍歷前半段鏈表和後半段鏈表,將後半段插入前半段
代碼
public void reorderList(ListNode head) {
if (head == null){
return;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next !=null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
if (fast == head){
return;
}
ListNode h = new ListNode(0);
h.next = slow.next;
slow.next = null;
ListNode cur = h.next;
ListNode newHead = new ListNode(0);
while (cur != null){
ListNode temp = cur;
cur = cur.next;
temp.next = newHead.next;
newHead.next = temp;
}
ListNode preInsert = head;
cur = newHead.next;
while (cur != null ){
ListNode temp = cur;
cur = cur.next;
temp.next = preInsert.next;
preInsert.next = temp;
preInsert = preInsert.next.next;
}
}