【leetcode】Sort List
2024-08-25 17:27:13
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
需要采用归并排序对链表进行操作。
归并排序思想:每次选取链表中间元素,把链表分割成两部分,
递归分割,直到链表中的元素是有序的时候(即只有一个元素时候),这时对链表进行合并,
合并的时候,每次选两个链表中小的元素放在下一个位置。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public: ListNode *mergeList(ListNode *h1,ListNode *h2)
{
ListNode *head=new ListNode();
ListNode *cur=head;
while(h1!=NULL&&h2!=NULL)
{
if(h1->val>h2->val)
{
cur->next=h2;
h2=h2->next;
}
else
{
cur->next=h1;
h1=h1->next;
} cur=cur->next;
} cur->next=h1==NULL?h2:h1; cur=head;
head=head->next;
delete cur; return head;
} ListNode *sortList(ListNode *head) { if(head==NULL||head->next==NULL) return head; ListNode *slow,*fast;
slow=fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
} ListNode *mid=slow->next;
slow->next=NULL; ListNode *h1=sortList(head);
ListNode *h2=sortList(mid);
return mergeList(h1,h2); }
};
最新文章
- linux基础快速掌握课件
- JS编码解码
- [ZigBee] 10、ZigBee之睡眠定时器
- native2ascii 国际资源文件编码
- 屠蛟之路_重登数据库大山_SecondDay
- ScrollView与TableView实现选择效果
- php笔记03:布尔类型,字符串,浮点数
- xxx is not in the sudoers file.This incident will be reported.的解决方法
- 使用alloctor模板来实现string类
- js 中的switch
- 增删查改-MySQL
- 7-21(排序) PAT排名汇总
- nginx常用场景
- [CSAcademy]Find the Tree
- en-zh(科学技术)science and technology-2
- Titanic缺失数值处理 &; 存活率预测
- input[type=";checkbox";]与label对齐
- yum使用过程中的常见错误
- 【DevExpress v17.2新功能预告】DevExtreme ASP.NET MVC新的强类型HTML Helpers
- mongo转换副本集