LeetCode147 Insertion Sort List 链表插入排序

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;
	}

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/87944953