请写一个单链表从大到小排序
时间: 2023-11-04 19:04:42 浏览: 76
一文梳理快速排序-从数组到单链表
好的,我可以回答这个问题。以下是将单链表从大到小排序的代码(使用冒泡排序):
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def bubbleSort(head):
if not head or not head.next:
return head
n = 0
p = head
while p:
n += 1
p = p.next
for i in range(n):
flag = False
cur = head
pre = None
while cur and cur.next:
if cur.val < cur.next.val:
flag = True
nxt = cur.next
cur.next = nxt.next
nxt.next = cur
if pre:
pre.next = nxt
else:
head = nxt
pre = nxt
else:
pre = cur
cur = cur.next
if not flag:
break
return head
```
这个函数接受一个链表的头节点作为输入,使用冒泡排序的方法将链表从大到小排序,并返回排序后的链表的头节点。
阅读全文