给出“链式线性表”的创建Create、显示Display、插入Insert、删除Delete、合并Merge
时间: 2023-12-13 16:03:54 浏览: 59
链式线性表是一种基于指针实现的动态数据结构,具有灵活性和高效性。下面是链式线性表的五个基本操作:
1. 创建Create:创建一个空的链式线性表。
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
```
2. 显示Display:遍历链表,输出所有元素的值。
```python
def display(self):
current = self.head
while current:
print(current.value)
current = current.next
```
3. 插入Insert:在链表的指定位置插入一个新元素。
```python
def insert(self, value, position):
new_node = Node(value)
if position == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for i in range(position - 1):
current = current.next
new_node.next = current.next
current.next = new_node
```
4. 删除Delete:删除链表中指定位置的元素。
```python
def delete(self, position):
if position == 0:
self.head = self.head.next
else:
current = self.head
for i in range(position - 1):
current = current.next
current.next = current.next.next
```
5. 合并Merge:将两个链表合并成一个新链表。
```python
def merge(self, other):
new_list = LinkedList()
current1 = self.head
current2 = other.head
while current1 and current2:
if current1.value < current2.value:
new_list.insert(current1.value, new_list.length())
current1 = current1.next
else:
new_list.insert(current2.value, new_list.length())
current2 = current2.next
while current1:
new_list.insert(current1.value, new_list.length())
current1 = current1.next
while current2:
new_list.insert(current2.value, new_list.length())
current2 = current2.next
return new_list
```
这些操作可以组成一个完整的链式线性表实现。
阅读全文