题目
leetcode 148
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
代码
非递归,自底向上。
struct ListNode *cutTwoList(struct ListNode *list, int len) {
if (list == NULL) return NULL;
struct ListNode *p = list, *q;
while (len > 1 && p->next != NULL) {
p = p->next;
len--;
}
q = p->next;
p->next = NULL;
return q;
}
void merge(struct ListNode **rear, struct ListNode *p, struct ListNode *q) {
while (p && q) {
if (p->val <= q->val) {
(*rear)->next = p;
p = p->next;
} else {
(*rear)->next = q;
q = q->next;
}
(*rear) = (*rear)->next;
}
if (p) (*rear)->next = p;
if (q) (*rear)->next = q;
while ((*rear)->next) (*rear) = (*rear)->next;
}
struct ListNode* sortList(struct ListNode* head){
struct ListNode *p = head, *q, ret, *rear;
rear = &ret;
ret.next = head;
int count = 1, len = 0;
while (p) {
len++;
p = p->next;
}
while (count < len) {
while (head) {
p = head;
q = cutTwoList(p, count);
head = cutTwoList(q, count);
merge(&rear, p, q);
p = ret.next;
}
head = ret.next;
rear = &ret;
count *= 2;
}
return ret.next;
}
(若对你有帮助,请不吝点赞)