使用快速排序对链表进行排序
本文代码使用python3语法
#链表节点
class Node():
def __init__(self,val):
self.val = val
self.prev = None
self.next = None
#链表
class LinkedList(object):
def __init__(self):
self.head = Node(-1)
#添加
def add(self,val):
temp = Node(val)
if self.head.next == None:
print("第一次add")
self.head.prev = temp
self.head.next = temp
temp.prev = self.head
temp.next = self.head
else:
self._add(temp)
def _add(self,node:Node):
#尾插
temp = self.head.prev #保留之前的
temp.next = node
node.next = self.head
self.head.prev = node
node.prev = temp
#顺序显示
def show(self):
p = self.head.next
while p and p != self.head:
print(p.val,end=" ")
p = p.next
print()
#逆序显示
def reverse(self):
p = self.head.prev
while p and p!=self.head:
print(p.val,end=' ')
p = p.prev
print()
#查找
def search(self,val):
if self.head.next == None:
print("还没有节点")
else:
self._search(val)
def _search(self,val):
p = self.head.next
while p != self.head:
if p.val == val:
return p
p = p.next
return None
#删除
def delete(self,val):
if self.head.next == None:
print("还没有节点")
else:
node = self._search(val)
if not node:
return 0
prev_ = node.prev
next_ = node.next
prev_ .next = next_
next_.prev = prev_
del(node)
#删第一个元素
def popleft(self):
if self.head.next == None:
print("还没有节点")
else:
temp = self.head.next
self.head.next = temp.next
temp.next.prev = self.head
return temp
#删除最后一个元素
def popright(self):
if self.head.next == None:
print("还没有节点")
else:
temp = self.head.prev
self.head.prev = temp.prev
temp.prev.next = self.head
#插入
def insert(self,index,val):
if self.head.next == None:
print("还没有节点")
else:
temp = Node(val)
p = self.head.next
while index:
p = p.next
index -= 1
prev_ = p.prev
prev_.next = temp
temp.next = p
p.prev = temp
temp.prev = prev_
def sort(self):
if self.head.next == None:
return
else:
self._sort(self.head.next,self.head.prev)
def inRight(self,base,target,scope):
#判断target是否在base节点的后面n,scope表示此次比较的范围,即[base,scope]
p = base.next
while p != scope.next:
if p == target:
return True
p = p.next
return False
def _sort(self,left,right):
#快排
if self.inRight(left,right,self.head):
base_val = left.val
l,r = left,right
while self.inRight(l,r,right):
while self.inRight(l,r,right) and r.val >= base_val:
r = r.prev
if self.inRight(l,r,right):
l.val = r.val
l = l.next
while self.inRight(l,r,right) and l.val < base_val:
l = l.next
if self.inRight(l,r,right):
r.val = l.val
r = r.prev
l.val = base_val
self._sort(left,l)
self._sort(l.next,right)
if __name__ == "__main__":
a = LinkedList()
a.add(10)
a.add(2)
a.add(3)
a.add(14)
a.add(15)
a.add(5)
a.add(5)
a.add(8)
a.add(9)
a.add(11)
a.add(12)
print("sort before:")
a.show()
a.sort()
print("sort after:")
a.show()
sort before:
10 2 3 14 15 5 5 8 9 11 12
sort after:
2 3 5 5 8 9 1011 12 14 15