是指在一个链表中删除指定位置上的节点。链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。
删除链表中给定位置的节点的步骤如下:
下面是一个示例代码,演示如何删除链表中给定位置的节点:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteNode(head, position):
if position < 0:
return head
if position == 0:
return head.next
curr = head
for _ in range(position - 1):
curr = curr.next
if curr is None:
return head
if curr.next is None:
return head
curr.next = curr.next.next
return head
# 示例用法
# 创建链表: 1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
# 删除位置为2的节点
new_head = deleteNode(head, 2)
# 输出链表: 1 -> 2 -> 4 -> 5
curr = new_head
while curr:
print(curr.val)
curr = curr.next
删除链表中给定位置的节点的应用场景包括但不限于:
腾讯云相关产品和产品介绍链接地址:
请注意,以上仅为示例,实际选择产品时应根据具体需求进行评估和选择。
领取专属 10元无门槛券
手把手带您无忧上云