Re: [閒聊] 每日LeetCode已回收
2095. Delete the Middle Node of a Linked List
刪除鏈結串列中間的節點。
Exaple:
https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png

Input: head = [1,3,4,7,1,2,6]
Output: [1,3,4,1,2,6]
Explanation:
The above figure represents the given linked list. The indices of the nodes
are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node.
思路:
1.用龜兔賽跑法,快指針走到底的時候,慢指針會在中間節點。
2.因為要刪除節點需要知道該節點的前個節點,所以fast從第一個節點開始往後跑,prev
因為要比fast慢所以令他為dummy,當下個節點或當前節點為null的時候,慢指針會停
在要被刪除的節點之前。
3.把prev的下個節點刪除
4.返回dummy.next
Java Code:
class Solution {
public ListNode deleteMiddle(ListNode head) {
ListNode dummy = new ListNode(-1, head);
ListNode prev = dummy;
ListNode fast = head;
while (fast != null && fast.next != null) {
prev = prev.next;
fast = fast.next.next;
}
prev.next = prev.next.next;
return dummy.next;
}
}
https://i.imgur.com/S1WiNS3.png


--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.111.108 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1665735900.A.7A2.html
推
10/14 16:25,
3年前
, 1F
10/14 16:25, 1F
推
10/14 16:26,
3年前
, 2F
10/14 16:26, 2F
→
10/14 16:26,
3年前
, 3F
10/14 16:26, 3F
推
10/14 16:27,
3年前
, 4F
10/14 16:27, 4F
推
10/14 16:28,
3年前
, 5F
10/14 16:28, 5F
推
10/14 16:31,
3年前
, 6F
10/14 16:31, 6F
推
10/14 17:03,
3年前
, 7F
10/14 17:03, 7F
討論串 (同標題文章)
完整討論串 (本文為第 46 之 719 篇):