重排單鏈表 LeetCode 8

鏈接:https://www.nowcoder.com/questionTerminal/3d281dc0b3704347846a110bf561ef6b?f=discussion
來源:牛客網

import java.util.List;
import java.util.Stack;
/*
將給定的單鏈表L: L 0→L 1→…→L n-1→L n,
重新排序爲: L 0→L n →L 1→L n-1→L 2→L n-2→…
要求使用原地算法,並且不改變節點的值
例如:
對於給定的單鏈表{1,2,3,4},將其重新排序爲{1,4,2,3}.
*/
public class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null)
return;
// 快慢指針找到中間節點
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//拆分鏈表,並反轉中間節點之後的鏈表
ListNode curNode = slow.next; //定義一個輔助curNode
slow.next = null; //將原來的鏈表拆分,拆分後的最後一個非空節點爲slow
ListNode preNode = null; //定義一個空的preNode,表示curNode之前的節點
while (curNode != null) {
ListNode nextNode = curNode.next; //
curNode.next = preNode; //當前節點的下一個節點指向前面的節點,即指針反轉
preNode = curNode; //preNode後移到curNode上
curNode = nextNode; //curNode後移

}
//執行完反轉操作之後,反轉鏈表的第一個節點爲preNode

    //合併兩個鏈表
    ListNode first = head;      //first指向第一個鏈表的頭結點
    ListNode after = preNode;   //after指向第二個反轉後的鏈表的頭結點
    while (first != null && after != null) {
        ListNode firstTemp = first.next;
        ListNode afterTemp = after.next;
        first.next = after;     //將after的第一個數放在first後面
        first = firstTemp;      //first後移到firstTemp
        after.next = first;     //after指向新的first
        after = afterTemp;      //after後移到afterTemp
    }
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章