LeetCode147 Insertion Sort List 链表插入排序

本文详细介绍了如何使用插入排序算法对链表进行排序,通过两种不同的实现方式展示了算法的具体步骤。第一种方法通过不断比较和插入元素来构建有序链表,而第二种方法则巧妙地利用了指针的指针来简化插入过程。

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

Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
 

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.


Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

题源:here;完整实现:here

思路:

其实思路就是按照冒泡算法的思路去写就可以了,如第一种实现(有点辣眼睛);但是,我们其实可以不用申请更多的内存就可以完成这个问题,当然也是参考的网上的思路。第二种写法最重要的一点是借用了指针的指针,完成了插入操作的简化,当然理解这个程序还是有难度的。

解体方案1

	ListNode* insertionSortList(ListNode* head) {
		ListNode *res = NULL;
		if (!head) return res;

		res = new ListNode(head->val);
		head = head->next;

		while (head) {
			int tmp = head->val;
			ListNode *r = res;
			while (r) {
				if (r->val < tmp) {
					if (!r->next) {
						r->next = new ListNode(tmp);
						break;
					}
					if (r->next && r->next->val >= tmp) {
						ListNode *r_next = r->next;
						r->next = new ListNode(tmp);
						r->next->next = r_next;
						break;
					}
				}
				else {
					ListNode *new_r = new ListNode(tmp);
					new_r->next = r;
					res = new_r;
					break;
				}
				r = r->next;
			}
			head = head->next;
		}

		return res;
	}

解体方案2

	ListNode *insertionSortList2(ListNode *head) {
		if (!head || !head->next) return head;

		ListNode *res = NULL;
		while (head) {
			ListNode *tmp_head = head;
			head = head->next;

			ListNode **tmp_res = &res;
			while (*tmp_res && (*tmp_res)->val < tmp_head->val) {
				tmp_res = &((*tmp_res)->next);
			}
			tmp_head->next = *tmp_res;
			*tmp_res = tmp_head;
		}
		return res;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值