leecode第一百四十八题(排序链表)
2024-10-16 07:15:38
class Solution {
public:
void sort_list(ListNode* head1, ListNode* head2,int len)//在原链表上进行排序
{
ListNode* cur_node1 = head1;
ListNode* cur_node2 = head1; while (cur_node2->next != head2)
cur_node2 = cur_node2->next; if (cur_node1->val > cur_node2->next->val)//必须先让cur_node1->val小于head2-》val
{
int temp = cur_node1->val;
cur_node1->val = cur_node2->next->val;
cur_node2->next->val = temp;
} while (len > )
{
while (cur_node1!= cur_node2->next && cur_node1->next->val < cur_node2->next->val)
cur_node1 = cur_node1->next;
if (cur_node1 == cur_node2->next)//说明head2的链表都小于head1
return;
else if(cur_node1 == cur_node2)//说明cur_node2->next后面没有统计,但是前面的都满足了
{
cur_node2 = cur_node2->next;
len--;
}
else//要交换了
{
ListNode* temp = cur_node2->next;
cur_node2->next = cur_node2->next->next;
temp->next = cur_node1->next;
cur_node1->next = temp;
len--;
}
}
} ListNode* sort_List(ListNode* head, int len)//归并排序
{
if (len == )
return NULL;
if (len == )
return head;
ListNode* mid_node = head;
for (int i = len / ; i > ; i--)
mid_node = mid_node->next; ListNode* left = sort_List(head, len / );
ListNode* right;
if (len & == )
{
right = sort_List(mid_node, len / + );
sort_list(left, right, len / + );
} else
{
right = sort_List(mid_node, len / );
sort_list(left, right, len / );
} return left;
} ListNode* sortList(ListNode* head) {//初试输入
int len = ;
ListNode* cur_node = head;
while (cur_node != NULL)
{
len++;
cur_node = cur_node->next;
} ListNode* res = sort_List(head, len);
return res;
}
};
分析:
为了满足时间复杂度,想到归并排序,为了满足空间复杂度,想到在原链表上进行排序。
但是在原链表上进行排序碰到问题有点多,尤其是不知道怎么判断终止条件和什么时候交换。
睡了一觉就想出来了。
时间击败63%,空间击败72%,室友说会不会是一晚上换了案例。。。。
说实话我还有点懵懂。
最新文章
- 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改
- HBase的数据模型相关操作 使用t这个变量来代替table1
- 合理利用 vs2013的性能分析跟诊断
- windows socket网络编程基础知识
- 从今天起,正式步入cnblogs,向曾经的脚印说声对不起!
- [Linux]Ubuntu下如何将普通用户提升到root权限
- html+css3实现网页时钟
- 15 3Sum(寻找三个数之和为指定数的集合Medium)
- Oracle SecureFiles 说明(转)
- Linux服务器杀马(转)
- APP测试(转载)
- 采用UltraISO制作U盘启动盘
- 【Netty】(5)源码 Bootstrap
- 手写JavaScript常用的函数
- ubuntu上安装并使用mysql数据库
- erlang并发编程
- Java对象之间的深度复制拷贝
- [Mac] How do I move a window whose title bar is off-screen?
- 托管调试助手 ";DisconnectedContext";:“上下文 0xf20540 已断开连接... 请确保在应用程序全部完成 RuntimeCallableWrapper (表示其内部的 COM 组件)之前,所有 COM 上下文/单元/线程都保持活动状态并可用于上下文转换
- Kali-linux分析密码
热门文章
- 渗透常用dos命令,http协议及数据提交方式。 hack 某某
- php导出超大csv导出方法,读取超大文件或者接受超大数组,防止内存溢出
- The missing package manager for macOS (or Linux)
- SQL[Err] ORA-00933: SQL command not properly ended
- μCOS-II移植 - 基于CortexM3
- java框架之Struts2(1)-简介及入门
- 2018-2019-1 20189203《Linux内核原理与分析》第二周作业
- GDI+案例
- django中的数据库迁移
- 【学习笔记】《Python从入门到实践》游戏-Alien Invasion