📅  最后修改于: 2023-12-03 15:07:16.427000             🧑  作者: Mango
给定一个单向链表和一个索引值,删除该索引值处的节点,并返回头节点的引用。
例如,给定链表为 [1, 2, 3, 4, 5],索引值为 2,则删除索引为 2 的节点后,链表变为 [1, 2, 4, 5],返回头节点 [1, 2, 4, 5] 的引用。
若删除的是头节点则返回新的头节点,如果删除的是链表中唯一的节点,则返回空值(None)。
可以考虑先找到索引值为 1 的节点,然后再将它的 next 节点指向其 next.next 节点。具体实现思路如下:
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def remove_node(head, index):
if head is None:
return None
# 删除头节点
if index == 0:
return head.next
# 找到索引值为 1 的节点
cur_node = head
count = 0
while cur_node:
count += 1
if count == index:
cur_node.next = cur_node.next.next
break
cur_node = cur_node.next
return head