Insertion Sort List - Leetcode

本文介绍了一种使用插入排序算法对链表进行排序的方法。通过将链表中的每个节点插入到已排序的部分,逐步构建出完全排序的链表。文章详细解释了插入过程,并提供了完整的Java代码实现。

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null)
			return head;

		ListNode cur = head.next;
		if (cur == null)
			return head;
		head.next = null;

		ListNode h = head, head2 = new ListNode(-1);
		head2.next = h;
		while (cur != null) {
			ListNode tmp = cur.next;
			h = head2.next;
			if (cur.val < h.val) {
				// insert befor h
				cur.next = h;
				h = cur;
				head2.next = h;
			} else {
				head2.next = h;
				ListNode pre = h;
				h = h.next;
				while (h != null && cur.val >= h.val) {
					pre = h;
					h = h.next;
				}
				// insert after pre
				pre.next = cur;
				cur.next = h;
			}
			cur = tmp;
		}
		return head2.next;
    }
}


思路:先回忆一下插入排序:最经典的方法是假设第一个是排好顺序了,为后面的每一个元素在排好序的空间找到正确的插入点即可。

题目中是链表实现,这里需要注意的是再链表中寻找正确的插入点。每次在链表中完成一个插入,都更新表头,方便下一轮搜索。

注意点:思路清楚,然后Java 的指针的使用方法。

Sort a linked list using insertion sort.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值