请给我一段简单的链表代码作示范
时间: 2023-11-14 13:04:37 浏览: 69
下面是一个简单的链表代码示例,实现了一个单向链表,并包含了添加节点、删除节点和遍历节点的基本操作:
```
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
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def remove_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 traverse(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
```
使用示例:
```
linked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.traverse() # 输出:1 2 3
linked_list.remove_node(2)
linked_list.traverse() # 输出:1 3
```
阅读全文