彼特文案-你身边的文案管家

彼特文案-你身边的文案管家

链表排序

59

链表排序是计算机科学中常见的算法问题,以下是几种常见的排序方法及其实现思路:

一、归并排序(推荐)

归并排序是链表排序的首选方法,时间复杂度为O(n log n),空间复杂度为O(log n)。

步骤:

分割链表:

使用快慢指针找到链表中点,将链表分成左右两部分。

递归排序:

对左右两部分分别递归调用归并排序。

合并链表:

将两个有序子链表合并成一个有序链表。

代码示例(Python):

```python

class ListNode:

def __init__(self, val=0, next=None):

self.val = val

self.next = next

def sortList(head: ListNode) -> ListNode:

if not head or not head.next:

return head

mid = findMiddle(head)

left = sortList(head)

right = sortList(mid.next)

return merge(left, right)

def findMiddle(head: ListNode) -> ListNode:

slow = head

fast = head.next

while fast and fast.next:

slow = slow.next

fast = fast.next.next

return slow

def merge(list1: ListNode, list2: ListNode) -> ListNode:

dummy = ListNode()

tail = dummy

while list1 and list2:

if list1.val < list2.val:

tail.next = list1

list1 = list1.next

else:

tail.next = list2

list2 = list2.next

tail = tail.next

tail.next = list1 or list2

return dummy.next

```

二、奇偶位排序

针对特殊结构的链表(奇数位升序、偶数位降序),可以先分离奇偶位节点,分别排序后再合并。

步骤:

分离链表:

将链表分为奇数位和偶数位两个子链表。

反转偶数位链表:

将偶数位链表反转。

合并链表:

将两个有序链表合并成一个有序链表。

代码示例(Python):

```python

def sortList(head: ListNode) -> ListNode:

if not head or not head.next:

return head

odd = head

even = head.next

while even and even.next:

odd.next = even.next

odd = odd.next

even.next = odd.next

even = even.next

odd.next = even 合并奇偶位链表

return mergeTwoLists(head, odd)

def mergeTwoLists(list1: ListNode, list2: ListNode) -> ListNode:

dummy = ListNode()

tail = dummy

while list1 and list2:

if list1.val < list2.val:

tail.next = list1

list1 = list1.next

else:

tail.next = list2

list2 = list2.next

tail = tail.next

tail.next = list1 or list2

return dummy.next

```

三、其他方法

选择排序:

时间复杂度O(n²),通过不断选择最小节点插入有序链表。

冒泡排序:

时间复杂度O(n²),通过相邻节点交换实现排序。

插入排序:

时间复杂度O(n²),通过构建有序链表,逐个插入新节点。

四、注意事项

归并排序是链表排序的推荐方法,尤其适合大规模数据。

奇偶位排序适用于特定结构链表,需先分离再合并。

其他简单算法(如选择排序、冒泡排序)仅适用于小规模数据,效率较低。

以上方法可根据具体需求选择实现,归并排序因其稳定性和高效性成为主流选择。