sort link list

题目描述

对一个单链表原地(in-place)排序。即直接对链表结点排序。返回排序后链表的头结点。

链表结点的定义为(请不要在代码中再次定义该结构):

C/C++
struct ListNode {
    int val;
    ListNode *next;
}

渣做法!N^2

ListNode* insert(ListNode* head, ListNode* item) {
	if (item == NULL) return head;
    if (head == NULL) { item->next = NULL; return item; }
	if (item->val < head->val) { item->next = head; return item;}
	ListNode* prev = head, *cur = head->next;
	while (cur != NULL) {
		if (cur->val < item->val) prev = cur, cur = cur->next;
		else {
			prev->next = item;
			item->next = cur;
			return head;
		}
	}

	if (cur == NULL) { 
		prev->next = item;
		item->next = NULL;
	}
	return head;
}
ListNode* sortLinkList(ListNode *head) {
	if (!head) return head;

	ListNode *cur = head, *newhead = NULL, *next;
	while (cur != NULL) {
		next = cur->next;
		newhead = insert(newhead, cur);
		cur = next;
	}
	return newhead;
}

 

 

 merge sort

ListNode* merge(ListNode* a, ListNode* b) {
	if (a == NULL || b == NULL) return a == NULL ? b : a;
	ListNode* head, *cur;
	if (a->val < b->val) head = a, a = a->next;
	else head = b, b = b->next;
	head->next = NULL;
	cur = head;
	while (a != NULL && b != NULL) {
		if (a->val < b->val) cur->next = a, cur = cur->next, a = a->next;
		else cur->next = b, cur = cur->next, b = b->next;
	}
	if (a != NULL) cur->next = a;
	else if (b != NULL) cur->next = b;
	else cur->next = NULL;
	return head;
}

ListNode* mergeSort(ListNode* start, int len) {
	if (len <= 0) return NULL;
	if (len == 1) return start;
	int mid = len / 2, t;
	ListNode *midnode = start;
	t = mid;
	while (t-- > 1) midnode = midnode->next;
	ListNode *start2 = midnode->next;
	midnode->next = NULL;
	return merge(mergeSort(start, mid), mergeSort(start2, len - mid));
}

ListNode* sortLinkList(ListNode *head) {
	ListNode* cur = head;
	int n = 0;
	while (cur != NULL) n++, cur = cur->next;
	return mergeSort(head, n);
}

 

 

 

你可能感兴趣的:(list)