实现不带头结点的双向循环链表的创建,实现该双向循环链表上数据的排序代码
时间: 2023-04-06 15:04:06 浏览: 128
好的,我可以回答这个问题。以下是实现不带头结点的双向循环链表的创建和排序的代码:
```python
# 定义双向循环链表节点类
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
# 定义双向循环链表类
class DoubleLinkedList:
def __init__(self):
self.tail = None
# 添加节点
def add_node(self, data):
new_node = Node(data)
if self.tail is None:
self.tail = new_node
self.tail.prev = self.tail
self.tail.next = self.tail
else:
new_node.prev = self.tail
new_node.next = self.tail.next
self.tail.next.prev = new_node
self.tail.next = new_node
# 排序
def sort(self):
if self.tail is None:
return
current = self.tail.next
while current != self.tail:
next_node = current.next
while next_node != self.tail.next:
if current.data > next_node.data:
current.data, next_node.data = next_node.data, current.data
next_node = next_node.next
current = current.next
# 打印链表
def print_list(self):
if self.tail is None:
return
current = self.tail.next
while current != self.tail:
print(current.data, end=' ')
current = current.next
print(self.tail.data)
# 测试
if __name__ == '__main__':
dll = DoubleLinkedList()
dll.add_node(3)
dll.add_node(1)
dll.add_node(4)
dll.add_node(2)
print('排序前:')
dll.print_list()
dll.sort()
print('排序后:')
dll.print_list()
```
希望这个代码能够帮到你!
阅读全文