请用python写一个简短的递归代码,能够按升序对链表的元素进行排序
时间: 2023-01-11 18:55:36 浏览: 108
一个基于链表的归并排序程序
下面是一个使用归并排序的简单递归代码:
```
# 定义链表的节点
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
# 归并排序函数
def merge_sort(head):
# 如果链表为空或只有一个元素,则直接返回
if not head or not head.next:
return head
# 将链表分成两半
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
# 对两半分别进行排序
left = merge_sort(head)
right = merge_sort(mid)
# 将两个有序链表合并
return merge(left, right)
# 合并两个有序链表的函数
def merge(left, right):
dummy = ListNode(0)
cur = dummy
while left and right:
if left.val < right.val:
cur.next = left
left = left.next
else:
cur.next = right
right = right.next
cur = cur.next
if left:
cur.next = left
if right:
cur.next = right
return dummy.next
```
希望这能帮到你!
阅读全文