1. 程式人生 > 其它 >Leecode no.143 重排連結串列

Leecode no.143 重排連結串列

package leecode;

/**
* 143. 重排連結串列
*
* 給定一個單鏈表 L 的頭節點 head ,單鏈表 L 表示為:
* L0 → L1 → … → Ln - 1 → Ln
* 請將其重新排列後變為:
* L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
* (說人話就是說把最後一個插到第一個後面,把倒數第二個插到第二個後面 以此類推...)
*
* @author TANG
* @date 2021/12/22
*/
public class ReorderList {


/**
* 第一次遍歷找到連結串列中間的位置
* 拆分成兩個連結串列
* 第二次遍歷 翻轉後半連結串列
*
* 第三次遍歷 兩個連結串列順序插入
*
* @param head
*/
public void reorderList(ListNode head) {
//第一步 快慢指標找到連結串列中點
ListNode slow = head;
ListNode fast = head;

//快指標走兩步 慢指標走一步 最後慢指標作為中點
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}

//第二步
//翻轉新連結串列
ListNode newList = slow.next;
slow.next = null;

//temp代表下一個要反轉的元素
if(newList == null) {
return;
}
ListNode temp = newList.next;
newList.next = null;
while(temp != null) {
ListNode tempNext = temp.next;
temp.next = newList;
newList = temp;
temp = tempNext;
}
//翻轉後起始元素是newList

//第三步 合併插入
while(head != null && newList != null) {
ListNode headNext = head.next;
ListNode newNext = newList.next;
head.next = newList;
newList.next = headNext;

head = headNext;
newList = newNext;
}



}

}