【面试算法题】单链表的快速排序

本文详细介绍了如何将快速排序算法应用于单链表,通过解析思路和展示代码实现,揭示了在链表环境下进行排序的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

在这里插入图片描述

代码实现

package qiuzhaoprepare;

class ListNode{
	int val;
	ListNode next;
	ListNode(int x){
		val = x;
	}
}
public class SingleListQuickSort {
    public ListNode partition(ListNode begin, ListNode end) {
        if(begin == end)
            return begin;
        
        int val = begin.val;
        ListNode p1 = begin;
        ListNode p2 = begin.next;
        
        while(p2 != end) {
            if(p2.val < val) {
                p1 = p1.next;
                
                int temp = p1.val;
                p1.val = p2.val;
                p2.val = temp;
            }
            p2 = p2.next;
        }
        int temp = begin.val;
        begin.val = p1.val;
        p1.val = temp;
        
        return p1;
    }
    public void quickSort(ListNode head, ListNode end) {
        if(head != end){
            ListNode node = partition(head, end);
            quickSort(head, node);
            quickSort(node.next, end);
        }
    }
    public void printSingleList(ListNode head) {
        while(head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(4);
        ListNode ListNode1 = new ListNode(2);
        ListNode ListNode2 = new ListNode(5);
        ListNode ListNode3 = new ListNode(3);
        ListNode ListNode4 = new ListNode(7);
        ListNode ListNode5 = new ListNode(9);
        ListNode ListNode6 = new ListNode(0);
        ListNode ListNode7 = new ListNode(1);
        head.next = ListNode1;
        ListNode1.next = ListNode2;
        ListNode2.next = ListNode3;
        ListNode3.next = ListNode4;
        ListNode4.next = ListNode5;
        ListNode5.next = ListNode6;
        ListNode6.next = ListNode7;
        SingleListQuickSort singleListQuickSort = new SingleListQuickSort();
        singleListQuickSort.quickSort(head, null);
        singleListQuickSort.printSingleList(head);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值