leetcode_148 Sort List
来源:互联网 发布:淘宝一直等待揽件陷阱 编辑:程序博客网 时间:2024/06/05 09:35
题目分析:
- 对链表进行排序,要求时间复杂度为O(nlogn),常量空间。
解题思路:
归并排序实现
基本思想:找到链表的中间节点,然后递归对前半部分和后半部分分别进行归并排序,然后将两个排好序的链表进行合并即可。
注意:如果数组进行归并排序,则空间不为常量空间。
实现程序
//找链表的中间节点struct ListNode *getMidList(struct ListNode *head){ if (head == NULL || head->next == NULL) return head; struct ListNode *p = head; struct ListNode *q = head; // 利用快慢指针查找中间节点 while (q != NULL && q->next != NULL && q->next->next != NULL) { p = p->next; q = q->next; q = q->next; } return p;}//两个链表的合并操作struct ListNode *mergeList(struct ListNode *a, struct ListNode *b){ struct ListNode *head = (struct ListNode *) malloc (sizeof(struct ListNode)); struct ListNode *cur = head; while (a != NULL && b != NULL) { if (a->val <= b->val) { cur->next = a; a = a->next; } else { cur->next = b; b = b->next; } cur = cur->next; } cur->next = a != NULL ? a : b; return head->next;}// 对链表进行归并排序 struct ListNode *sortList(struct ListNode *head){ if (head == NULL || head->next == NULL) return head; // 获取中间及诶单 struct ListNode *mid = getMidList(head); struct ListNode *next = mid->next; mid->next = NULL; // 对前半部分和后半部分递归进行归并排序 return mergeList(sortList(head), sortList(next));}
0 0
- leetcode_148 Sort List
- list sort
- list sort
- Sort List
- Sort List
- list - sort
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- LeetCode 1.Two Sum
- android布局 FrameLayout(帧布局)详解
- 一个Strus2的简单示例(核心控制器 StrusPrepareAndExecuteFilter)
- redis持久化AOF与RDB
- redis持久化AOF与RDB配置
- leetcode_148 Sort List
- c++第3次作业
- Linux内核创建一个新进程的过程
- 分布式配置 tachyon 并运行Hadoop例子 MapReduce
- Incorrect string value: '\xC2\x8B\xC3\xA8\xC2\xAF...' for column 'name' at row 1
- JavaWeb分页技术总结
- The method getSupportFragmentManager() is undefined for the type
- 1015 milk produce
- poj-1833-排列 stl next_permutation(a,a+n)