创建整型数据的List实现双向链表,向链表头部依次插入数据34,56,78;向链表尾部依次插入数据23,98,99;使用迭代器输出链表,输出链表的最大值,删除数值98;使用sort函数对数组进行从小到大排序并输出。
时间: 2023-07-11 08:06:24 浏览: 193
下面是一份 Python 代码实现:
```python
class Node:
def __init__(self, data=None, prev=None, next=None):
self.data = data
self.prev = prev
self.next = next
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_at_head(self, data):
new_node = Node(data, None, self.head)
if self.head is not None:
self.head.prev = new_node
self.head = new_node
if self.tail is None:
self.tail = new_node
def insert_at_tail(self, data):
new_node = Node(data, self.tail, None)
if self.tail is not None:
self.tail.next = new_node
self.tail = new_node
if self.head is None:
self.head = new_node
def __iter__(self):
node = self.head
while node is not None:
yield node.data
node = node.next
def find_max(self):
max_value = self.head.data
node = self.head.next
while node is not None:
if node.data > max_value:
max_value = node.data
node = node.next
return max_value
def delete(self, data):
node = self.head
while node is not None:
if node.data == data:
if node.prev is not None:
node.prev.next = node.next
else:
self.head = node.next
if node.next is not None:
node.next.prev = node.prev
else:
self.tail = node.prev
return
node = node.next
def sort(self):
sorted_list = sorted(self)
self.head = None
self.tail = None
for data in sorted_list:
self.insert_at_tail(data)
# 创建双向链表并插入数据
lst = DoublyLinkedList()
lst.insert_at_head(34)
lst.insert_at_head(56)
lst.insert_at_head(78)
lst.insert_at_tail(23)
lst.insert_at_tail(98)
lst.insert_at_tail(99)
# 输出链表
for data in lst:
print(data, end=' ')
print()
# 输出最大值
print('Max value:', lst.find_max())
# 删除数值98
lst.delete(98)
# 输出删除后的链表
for data in lst:
print(data, end=' ')
print()
# 排序并输出
lst.sort()
for data in lst:
print(data, end=' ')
print()
```
输出结果为:
```
78 56 34 23 98 99
Max value: 99
78 56 34 23 99
23 34 56 78 99
```
阅读全文