编程实现单向链表建立、删除、插入、输出
时间: 2023-09-25 11:12:17 浏览: 48
下面是 Python 语言的单向链表实现:
```python
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, val):
if self.head is None:
self.head = ListNode(val)
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = ListNode(val)
def delete(self, val):
if self.head is None:
return
if self.head.val == val:
self.head = self.head.next
return
curr = self.head
while curr.next is not None:
if curr.next.val == val:
curr.next = curr.next.next
return
curr = curr.next
def insert(self, val, pos):
if pos == 0:
new_node = ListNode(val)
new_node.next = self.head
self.head = new_node
return
curr = self.head
for i in range(1, pos):
if curr is None:
return
curr = curr.next
if curr is None:
return
new_node = ListNode(val)
new_node.next = curr.next
curr.next = new_node
def print_list(self):
curr = self.head
while curr is not None:
print(curr.val, end=" ")
curr = curr.next
print()
```
其中,ListNode 表示链表的节点,LinkedList 表示链表。append 方法在链表末尾插入一个元素,delete 方法删除链表中指定值的节点,insert 方法在指定位置插入一个元素,print_list 方法按顺序输出链表中的所有元素。