111. Insertion Sort List
来源:互联网 发布:mac如何强制关闭软件 编辑:程序博客网 时间:2024/06/08 11:20
-147. Insertion Sort List
Total Accepted: 73736 Total Submissions: 246747 Difficulty: Medium
Sort a linked list using insertion sort.
Subscribe to see which companies asked this question
主要思路:
时间复杂度
空间复杂度
主要思路:逻辑上想象有两条链表
物理上还是一条
每次移动到一个元素将其插入已经有序的新链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* insertionSortList(ListNode* head) { if(head==NULL) return NULL; ListNode *p=head->next,*pnext,*prep=head; head->next = NULL; ListNode *q=head,*qnext,*tmp; while(p){ q = head; if(p->val<= q->val){//如果可以在最前面插入 pnext = p->next; p->next = head; head = p; //更新头部 p = pnext; } else{ while(q!=NULL){ //找到当前节点小于目标,下一节点大于目标 qnext = q->next; if(qnext==NULL)break; if(qnext!=NULL&&qnext->val>p->val)break; q = qnext; } if(qnext==NULL) {//如果需要插入末尾 q->next = p; p=p->next; q->next->next = NULL; //注意第二条链末尾置为空 } else { //如果是插入中间 pnext = p->next; p->next = q->next; q->next = p; p = pnext; } } } return head; }};
0 0
- 111. Insertion Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List
- Leetcode: Insertion Sort List
- [LeeCode] Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- [LeetCode] Insertion Sort List
- 二叉树的创建与遍历2
- C++学习笔记(1) 顺序容器简介
- 在vs如何查看汇编代码
- oracle常用函数汇总——临时表
- 40个Java集合问题
- 111. Insertion Sort List
- 不同厂家的电脑进入bios的快捷键整理汇总
- Windows下使用VisualSVN Server搭建SVN服务器
- June 11th 模拟赛B T2 翻山越岭 Solution
- CSS——样式设置技巧(居中和隐藏)
- 多线程中使用信号机制 pthread_sigmask()
- Linux i2c子系统
- USACO 3.4American Heritage 中序,前序构建二叉树
- tomcat部署项目如何去掉项目名称