理解Python的链表ListNode
warning:
这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
ListNode是一个在进行链表操作时常用的数据结构,它通常用于表示链表中的一个节点。在Python中,我们可以通过定义一个类来实现ListNode。
以下是一个简单的实现:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next在这个定义中,ListNode有一个值域(val)和一个指向下一个节点的指针(next)。
以下是一些使用ListNode的常见操作:
- 创建链表
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3- 遍历链表
current = node1
while current is not None:
print(current.val)
current = current.next- 添加节点
new_node = ListNode(4)
node1.next = new_node
new_node.next = node2- 删除节点
node1.next = node2.next- 查找节点
current = node1
while current is not None and current.val != value:
current = current.next
return current- 插入节点
current = node1
while current.next is not None and current.next.val < new_node.val:
current = current.next
new_node.next = current.next
current.next = new_node- 删除节点
current = node1
while current.next is not None and current.next.val != value:
current = current.next
current.next = current.next.next以上就是ListNode的一些基本操作,在实际应用中,你可以根据需要进行相应的扩展和修改。
评论已关闭