文章目錄
- 題目
- 解法一(快慢指標 + 反轉 + 合并)
- 方法一代碼
- 解法二 (借助線性表)
- 將鏈表存入到 線性表中, 通過下標 進行 插入 尾結點,
- 代碼
- 附圖
題目

?
解法一(快慢指標 + 反轉 + 合并)
利用 雙指標 確定 中間的節點,以中間節點為界限,將鏈表分割為上下兩個部分,
隨后將 后半部分反轉
最后一步 : 合并 l1 和 l2,
?
方法一代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
// 無回傳值
public void reorderList(ListNode head) {
if( head == null){
return;
}
// 得到中間節點
ListNode mid = myMidNode(head);
// 分割鏈表
ListNode l1 = head;
ListNode l2 = mid.next;
mid.next = null;
// 下部分鏈表 反轉
l2 = myReverse(l2);
// 上下兩部分鏈表合并
mergeLinked(l1,l2);
}
public static void mergeLinked(ListNode l1,ListNode l2){
ListNode l1_tmp = null;// 用來記錄 l1 的 next
ListNode l2_tmp = null;// 用來記錄 l2 的 next
while(l1!=null && l2 != null){
l1_tmp = l1.next;
l2_tmp = l2.next;
l1.next = l2;
l1 = l1_tmp;
l2.next = l1;
l2 = l2_tmp;
}
}
public static ListNode myReverse(ListNode head){
ListNode prev = null;
ListNode cur = head;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = prev;
prev = cur;
cur = curNext;
}
return prev;
}
public static ListNode myMidNode(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow =slow.next;
}
return slow;
}
}

?
解法二 (借助線性表)
將鏈表存入到 線性表中, 通過下標 進行 插入 尾結點,
代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if( head == null){
return;
}
List<ListNode> list = new ArrayList<>();
ListNode node = head;
while(node!=null){
list.add(node);
node = node.next;
}
int n = list.size();
int j = n -1;
int i = 0;
while(i < j){
list.get(i).next = list.get(j);
i++;
if(i == j){
break;
}
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}

附圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395107.html
標籤:java



