如何用Python和C语言编写代码删除链表中的节点?

2026-05-22 03:030阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计630个文字,预计阅读时间需要3分钟。

如何用Python和C语言编写代码删除链表中的节点?

给定向量链表的头指针和一个要删除的节点的值,定义一个函数删除该节点,并返回删除后的链表的头节点。

pythonclass ListNode: def __init__(self, value=0, next=None): self.value=value self.next=next

def delete_node(head, val): if not head: return None

if head.value==val: return head.next

current=head while current.next and current.next.value !=val: current=current.next

if current.next: current.next=current.next.next

return head

示例head=ListNode(4, ListNode(5, ListNode(1, ListNode(9))))val=5new_head=delete_node(head, val)while new_head: print(new_head.value, end= ) new_head=new_head.next

输出结果:

41 9

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

阅读全文
标签:节点

本文共计630个文字,预计阅读时间需要3分钟。

如何用Python和C语言编写代码删除链表中的节点?

给定向量链表的头指针和一个要删除的节点的值,定义一个函数删除该节点,并返回删除后的链表的头节点。

pythonclass ListNode: def __init__(self, value=0, next=None): self.value=value self.next=next

def delete_node(head, val): if not head: return None

if head.value==val: return head.next

current=head while current.next and current.next.value !=val: current=current.next

if current.next: current.next=current.next.next

return head

示例head=ListNode(4, ListNode(5, ListNode(1, ListNode(9))))val=5new_head=delete_node(head, val)while new_head: print(new_head.value, end= ) new_head=new_head.next

输出结果:

41 9

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

阅读全文
标签:节点