这是力扣的 2095 题,难度为中等,解题方案有很多种,本文讲解我认为最奇妙的一种。
慢慢开始链表的模块了,这道题是一道非常好的队列的例题,很有代表性。
给你一个链表的头节点 head
。删除 链表的 中间节点 ,并返回修改后的链表的头节点 head
。
长度为 n
链表的中间节点是从头数起第 ⌊n / 2⌋
个节点(下标从 0 开始),其中 ⌊x⌋
表示小于或等于 x
的最大整数。
n
= 1
、2
、3
、4
和 5
的情况,中间节点的下标分别是 0
、1
、1
、2
和 2
。示例 1:
输入:head = [1,3,4,7,1,2,6]
输出:[1,3,4,1,2,6]
解释:
上图表示给出的链表。节点的下标分别标注在每个节点的下方。
由于 n = 7 ,值为 7 的节点 3 是中间节点,用红色标注。
返回结果为移除节点后的新链表。
示例 2:
输入:head = [1,2,3,4]
输出:[1,2,4]
解释:
上图表示给出的链表。
对于 n = 4 ,值为 3 的节点 2 是中间节点,用红色标注。
示例 3:
输入:head = [2,1]
输出:[2]
解释:
上图表示给出的链表。
对于 n = 2 ,值为 1 的节点 1 是中间节点,用红色标注。
值为 2 的节点 0 是移除节点 1 后剩下的唯一一个节点。
提示:
[1, 105]
内1 <= Node.val <= 105
这个算法的目的是从链表中删除中间的节点,而保持链表的其余部分不变。给定链表的头结点 head
,该方法返回删除中间节点后的链表。
思路与算法:
null
。fast
和一个慢指针 slow
。开始时,fast
和 slow
都指向链表的头部。fast
指针移动到倒数第二个节点时(即当前节点是中间节点的前一个节点),停止移动 fast
指针。同时,移动 slow
指针,使其指向下一个节点。slow.next
指向 slow.next.next
,从而删除中间节点。head
。链表算法的一般思路解法包括以下几个方面:
Java版本:
class Solution {
public ListNode deleteMiddle(ListNode head) {
if (head.next == null) {
return null;
}
ListNode fast = head;
ListNode slow = new ListNode(-1, head);
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
Pyhton版本:
class Solution:
def deleteMiddle(self, head: ListNode) -> ListNode:
if head.next is None:
return None
fast = head
slow = ListNode(-1, head)
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
slow.next = slow.next.next
return head
C++版本:
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if (head->next == nullptr) {
return nullptr;
}
ListNode* fast = head;
ListNode* slow = new ListNode(-1, head);
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};
Go版本:
type ListNode struct {
Val int
Next *ListNode
}
func deleteMiddle(head *ListNode) *ListNode {
if head.Next == nil {
return nil
}
fast := head
slow := &ListNode{Val: -1, Next: head}
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
slow.Next = slow.Next.Next
return head
}