无头结点的单链表python代码
时间: 2023-05-28 15:05:25 浏览: 80
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def delete_node(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
current = self.head
while current.next is not None:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
def print_list(self):
current = self.head
while current is not None:
print(current.data, end=' ')
current = current.next
# create a linked list
my_list = LinkedList()
# add nodes
my_list.add_node(1)
my_list.add_node(2)
my_list.add_node(3)
my_list.add_node(4)
# print the list
my_list.print_list()
# delete a node
my_list.delete_node(3)
# print the updated list
my_list.print_list()
阅读全文