[LeetCode]147 链表插入排序
来源:互联网 发布:2012年3d开奖数据 编辑:程序博客网 时间:2024/05/17 23:03
Insertion Sort List(链表插入排序)
【难度:Medium】
Sort a linked list using insertion sort.
对一个链表使用插入排序。
解题思路
基于插入排序的思想,从链表头开始遍历,找到第一个大于当前节点的链表节点,进行链表间的交换操作。由于链表的操作比较麻烦,因此链表的插入排序相比于数组的插入排序要复杂。
c++代码如下:
/** * 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 || !head->next) return head; //虚节点作为新链表头 ListNode* dummy = new ListNode(INT_MIN); //遍历节点 ListNode* cur = head; //cur节点的前一个节点 ListNode* pre = dummy; //cur节点的下一个节点 ListNode* cur_next = NULL; while (cur) { //先保留cur的下一个节点 cur_next = cur->next; //pre的下一个节点的值大于cur节点的值 while (pre->next && pre->next->val < cur->val) pre = pre->next; //增加新链表中的节点 cur->next = pre->next; pre->next = cur; pre = dummy; cur = cur_next; } //去掉虚节点 return dummy->next; }};
数组的插入排序c++代码如下:
#include<iostream>#include<vector> using namespace std;void insertSort(vector<int>& array) { int n = array.size(); for (int i = 1; i < n; i++) { //找到比前面一个数更小的 if (array[i-1] > array[i]) { int current = array[i]; int j = i; //找到合适的插入位置 while (j > 0 && array[j-1] > current) { array[j] = array[j-1]; j--; } array[j] = current; } }}
0 0
- [LeetCode]147 链表插入排序
- LeetCode 147 Insertion Sort List(链表插入排序)
- leetcode 刷题:插入排序链表
- 使用插入算法排序链表,leetcode
- 【leetcode】插入排序一个链表
- leetcode之链表类之链表排序-----147/148. 链表快速排序 链表插入排序
- Insertion Sort List 链表插入排序@LeetCode
- LeetCode:Insertion Sort List//链表插入排序
- leetcode Insertion Sort List(链表插入排序)
- LeetCode | Insertion Sort List(插入法排序链表)
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- Leetcode Insertion Sort List 插入排序链表
- LeetCode Insertion Sort List 链表的插入排序
- leetcode 147. Insertion Sort List-链表插入排序
- leetcode钻研5 链表的插入排序
- [LeetCode] Insertion Sort List 单向链表插入排序
- LeetCode-147. Insertion Sort List (JAVA)链表插入排序
- leetcode 147. Insertion Sort List 链表插入排序
- javascript 事件模型
- 计算机专业英语 学习笔记 6
- CSDN博客以后不再使用,转移到博客园了(http://www.cnblogs.com/dongc/)
- Poi实现Excel导出工具类封装
- iOS9 的白名单问题
- [LeetCode]147 链表插入排序
- Android 蓝牙对等通信初探
- 复数类的基本功能实现
- ORM
- [bzoj3545]Peaks [bzoj3551]Peaks加强版
- AMiner背后的技术细节与挑战
- rebmuNelgniS.136
- 数据一致性和事物管理
- SpringMVC处理Date类型的成员变量方法