📅  最后修改于: 2023-12-03 15:37:05.479000             🧑  作者: Mango
双链表是一种链表数据结构,它拥有两个指向相邻节点的引用,即前驱和后继指针。插入排序是一种简单有效的排序算法,通过将未排序的元素依次插入到已排序的序列中,最终得到一个有序序列。
双链表的插入排序就是采用双链表作为排序数据结构,结合插入排序算法来实现排序的过程。
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_sorted(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
return
current = self.head
while current is not None:
if current.value > new_node.value:
if current == self.head:
new_node.next = current
current.prev = new_node
self.head = new_node
else:
new_node.next = current
new_node.prev = current.prev
current.prev.next = new_node
current.prev = new_node
return
if current.next is None:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
return
current = current.next
def insertionsort(self):
if self.head is None:
return
current = self.head.next
while current is not None:
value = current.value
self.delete(current)
self.insert_sorted(value)
current = current.next
def delete(self, node):
if node == self.head:
self.head = node.next
if self.head is not None:
self.head.prev = None
elif node == self.tail:
self.tail = node.prev
if self.tail is not None:
self.tail.next = None
else:
node.prev.next = node.next
node.next.prev = node.prev
def display(self):
current = self.head
while current is not None:
print(current.value, end=" ")
current = current.next
print()
if __name__ == '__main__':
linked_list = DoublyLinkedList()
linked_list.insert_sorted(3)
linked_list.insert_sorted(1)
linked_list.insert_sorted(5)
linked_list.insert_sorted(2)
linked_list.insert_sorted(4)
linked_list.display()
# Output: 1 2 3 4 5
linked_list.insertionsort()
linked_list.display()
# Output: 1 2 3 4 5
双链表的插入排序是一种简单有效的排序算法。通过结合双链表的特点和插入排序算法的思想,实现了一种高效的排序方法。