单链表的快排

单链表的快排和普通快排都是快排

1.移动数(partition),使得左边的都小于key, 右边的都大于key

2.反复

下面是正常数组的快排:

def arr_sort(self, vector,start, end):
        #start, end = 0, len(vector)-1
        i,j = start ,end
        if i>=j:
            return 
        key = vector[start]
        while i<j:
            while i<j and vector[j]>= key:
                j-=1
            vector[i] = vector[j]
            
            while i<j and vector[i] <= key:
                i+=1
            vector[j] = vector[i]
            
        vector[j] = key
        self.arr_sort(vector, start,i-1)
        self.arr_sort(vector, j+1, end)

 单链表的快排需要重写partition:

    def partition(self, head, end):
        p = head
        q = p.next
        key = head.val
        while q !=end:
            if q.val < key:
                p = p.next
                p.val, q.val = q.val, p.val
            q = q.next
        p.val, head.val = head.val, p.val
        return p
    def list_sort(self,head, end):
        p = self.partition(head, end)
        self.list_sort(head,p)
        self.list_sort(p.next,end)
         

快速排序是一种常用的排序算法,通常用于数组,但对于链表,由于链表的特点不适合原地交换元素,所以我们将采用分治思想,找到链表中的最小节点并将其调整到链表头部。以下是使用C语言实现这一操作的一个简化版算法: ```c #include <stdio.h> #include <stdlib.h> // 链表节点结构体 typedef struct ListNode { int data; struct ListNode* next; } ListNode; // 获取链表头节点 ListNode* findMin(ListNode* head) { if (head == NULL || head->next == NULL) { return head; } ListNode* minNode = head; while (minNode->next != NULL) { if (minNode->data > minNode->next->data) { minNode = minNode->next; } } return minNode; } // 将链表的最小节点移动到链表头部 void moveMinToFront(ListNode** head_ref) { ListNode* minNode = findMin(*head_ref); if (minNode == *head_ref) { // 如果是最小节点,则无需移动 return; } // 更新最小节点前驱节点的指针 ListNode* prev = NULL; ListNode* current = *head_ref; while (current != minNode) { prev = current; current = current->next; } prev->next = minNode->next; // 移动最小节点到头 minNode->next = *head_ref; *head_ref = minNode; } // 打印链表 void printList(ListNode* head) { while (head != NULL) { printf("%d -> ", head->data); head = head->next; } printf("NULL\n"); } int main() { // 创建示例链表 ListNode* list = malloc(sizeof(ListNode)); list->data = 5; list->next = malloc(sizeof(ListNode)); list->next->data = 3; list->next->next = malloc(sizeof(ListNode)); list->next->next->data = 7; list->next->next->next = malloc(sizeof(ListNode)); list->next->next->next->data = 2; list->next->next->next->next = NULL; printf("Original List:\n"); printList(list); moveMinToFront(&list); // 移动最小节点 printf("\nModified List with minimum at the front:\n"); printList(list); return 0; } ``` 这个程序首先创建了一个简单的单链表,然后通过`findMin`函数找出链表中的最小节点,接着在`moveMinToFront`函数中通过迭代找到最小节点的前驱节点并更新指针,最后把最小节点插入到链表头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值