2024-02-29|閱讀時間 ‧ 約 0 分鐘

串列應用: 刪除鏈結串列的中央節點_Leetcode #2095_Leetcode精選75題

題目敘述

題目會給定我們一條鏈結串列Linked list的起始節點,要求我們刪除Linked List正中央的節點

註:

正中央的節點,題目定義為索引為floor( 串列長度 / 2 ) 的節點,索引從零(Head Node)出發開始數。

例如

1 -> 2 -> 3 -> 4
鏈結串列長度為4,floor( 4 / 2) = 2,索引為二的節點是3,把Node 3移除。

答案是

1 -> 2 -> 4


題目的原文敘述


Constraints:

  • The number of nodes in the list is in the range [1, 10^5].

鏈結串列的長度介於1 ~ 十萬 之間。

  • 1 <= Node.val <= 10^5

每個節點的Node value介於 1~ 十萬 之間。


測試範例

Example 1:

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.

Example 2:

Input: head = [1,2,3,4]
Output: [1,2,4]
Explanation:
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.

Example 3:

Input: head = [2,1]
Output: [2]
Explanation:
The above figure represents the given linked list.
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.

演算法 雙指針 用快/慢指針定位中央節點

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.