(1)实现单链表的创建; (2)实现单链表的插入; (3)实现单链表的删除 (4)实现单链表的查找; (5)实现单链表的显示; 两个线性表合并算法的实现。已知顺序表LA和LB中的数据元素按值非递减有序排列,现要将LA和LB归并为一个新的顺序表LC,且LC中的数据元素仍按值非递减有序排序。例如: LA= (3,5,8,11) LB= (2,6,9,15,20)。
时间: 2023-05-13 17:06:24 浏览: 104
单链表的创建,排序,归并,插入删除定位和获得元素,计算元素个数,打印链表
以下是单链表的创建、插入、删除、查找和显示的代码实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(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 delete(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 search(self, data):
current = self.head
while current is not None:
if current.data == data:
return True
current = current.next
return False
def display(self):
current = self.head
while current is not None:
print(current.data, end=' ')
current = current.next
print()
# 创建单链表
llist = LinkedList()
llist.insert(1)
llist.insert(2)
llist.insert(3)
llist.insert(4)
# 插入元素
llist.insert(5)
# 删除元素
llist.delete(3)
# 查找元素
print(llist.search(2)) # True
print(llist.search(6)) # False
# 显示单链表
llist.display()
```
以下是两个线性表合并算法的实现:
```python
def merge_lists(la, lb):
lc = []
i = j = 0
while i < len(la) and j < len(lb):
if la[i] <= lb[j]:
lc.append(la[i])
i += 1
else:
lc.append(lb[j])
j += 1
lc += la[i:]
lc += lb[j:]
return lc
# 两个顺序表合并
la = [3, 5, 8, 11]
lb = [2, 6, 9, 15, 20]
lc = merge_lists(la, lb)
print(lc) # [2, 3, 5, 6, 8, 9, 11, 15, 20]
```
阅读全文