给我编写一个程序内容为 建立单链表,并在单链表上实现插入、删除和查找操作
时间: 2023-05-31 21:07:42 浏览: 112
好的,我可以帮您编写一个建立单链表并实现插入、删除、查找的程序。以下是示例代码:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, val):
new_node = Node(val)
if not self.head:
self.head = new_node
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = new_node
def delete(self, val):
curr = self.head
prev = None
while curr and curr.val != val:
prev = curr
curr = curr.next
if curr:
if prev:
prev.next = curr.next
else:
self.head = curr.next
def search(self, val):
curr = self.head
while curr and curr.val != val:
curr = curr.next
return curr
# 示例程序
ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
ll.delete(2)
assert ll.search(1).val == 1
assert not ll.search(2)
assert ll.search(3).val == 3
```
这个程序实现了一个单链表,可以进行插入、删除、查找等操作。如果您希望更深入的了解单链表的实现和操作,建议您查阅相关的资料或者学习数据结构的相关课程。
阅读全文