5种链表排序算法(多语言描述)

148. 排序链表

与数组的排序算法相比,由于链表不支持随机访问,故不能使用堆排序希尔排序,因为他们都依赖于对下标的运算和随机访问某一下标的元素

冒泡排序

C++

int listLength(ListNode* head) {
   
   
    int l = 0;
    while (head) {
   
   
        l++;
        head = head->next;
    }
    return l;
}

ListNode* bubbleSort(ListNode* head) {
   
   
    if (head == nullptr || head->next == nullptr)
        return head;
    int N = listLength(head);
    bool sorted = false;
    while (!sorted) {
   
   
        sorted = true;
        auto p1 = head, p2 = head->next;
        for (int i = 0; i < N && p1 && p2; i++) {
   
   
            if (p1->val > p2->val) {
   
   
                swap(p1->val, p2->val);
                sorted = false;
            }
            p1 = p1->next;
            p2 = p2->next;
        }
        N--;
    }
    return head;
}

Python

def listLength(head):
    l = 0
    while head:
        l += 1
        head = head.next
    return l

def bubbleSortList(head):
    if head is None or head.next is None:
        return head
    N = listLength(head)
    sorted = False
    while not sorted:
        sorted = True
        p1, p2 = head, head.next
        for i in range(0, N - 1):
            if not (p1 and p2):
                break
            if p1.val > p2.val:
                p1.val, p2.val = p2.val, p1.val
                sorted = False
            p1, p2 = p1.next, p2.next
        N -= 1
    return head

Golang

func listLength(head *ListNode) int {
   
   
    l := 0
    for head != nil {
   
   
        l++
        head = head.Next
    }
    return l
}

func bubbleSortList(head *ListNode) *ListNode{
   
   
    if head == nil || head.Next == nil {
   
   
        return head
    }
    N := listLength(head)
    sorted := false
    for !sorted {
   
   
        sorted = true
        p1, p2 := head, head.Next
        for i := 0; i < N && p1 != nil && p2 != nil; i++ {
   
   
            if p1.Val > p2.Val {
   
   
                p1.Val, p2.Val = p2.Val, p1.Val
                sorted = false
            }
            p1, p2 = p1.Next, p2.Next
        }
    }
    return head
}

插入排序

C++

ListNode* cutHead(ListNode*& head) {
   
   
    if (!head)
        return head;
    auto res = head;
    head = head->next;
    res->next = nullptr;
    return res;
}

ListNode* insertionSortList(ListNode* head) {
   
   
    if (head == nullptr || head->next == nullptr)
        return head;

    auto dummy = new ListNode(0, cutHead(head));
    while (head) {
   
   
        auto p = cutHead(head);
        auto n = dummy;
        while (n->next && p->val >= n->next->val) {
   
   
            n = n->next;
        }
        p->next = n->next;
        n->next = p;
    }

    auto res = dummy->next;
    delete dummy;
    return res;
}

Python

def cut_head(head)<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值