链表插入排序
来源:互联网 发布:java设计模式 百度云 编辑:程序博客网 时间:2024/05/23 14:20
链表插入排序
题目描述:用插入排序法对链表进行排序
given 1->3->2->0->NULL, return 0->1->2->3->NULL
算法描述:
算法一:将题目中给出的链表数据结构转换为C++标准库中的标准list数据结构,调用c++标准库中的list算法进行排序即可完成
算法二:将题目中给出的链表数据结构转换为vrector,对vector进行插入排序,插入排序的算法如下所示:
vector<int> insertSort(vector<int> a, int length) { int key,i; for(int j = 1;j<length;j++) { key = a[j]; i = j; while(i>0 && a[i-1] > key) { a[i] = a[i-1]; i = i-1; } a[i] = key; } return a; }
插入排序的整体思想类似于玩扑克牌游戏摸牌阶段整理扑克牌顺序的思想。再对排序好的vector创建为list。创建list的代码如下:
ListNode* createList(vector<int>a, int length) { ListNode * head, *tail, *mid; head = tail = NULL; int i = 0; while (i < length) { mid = new ListNode(-1); mid->val = a[i]; mid->next = NULL; if (head == NULL) { head = mid; } else { tail->next = mid; } tail = mid; i++; } return head; }
则解决该问题的整体代码如下:
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */class Solution {public: /** * @param head: The first node of linked list. * @return: The head of linked list. */ ListNode *insertionSortList(ListNode *head) { // write your code here //step one: List 2 vector vector<int> raw_data; vector<int> mid_data; ListNode* result; while(head != NULL) { raw_data.push_back(head->val); head = head ->next; } //step two: sorting mid_data = insertSort(raw_data,raw_data.size()); //step three: vector 2 list result = createList(mid_data,raw_data.size()); return result; } vector<int> insertSort(vector<int> a, int length) { int key,i; for(int j = 1;j<length;j++) { key = a[j]; i = j; while(i>0 && a[i-1] > key) { a[i] = a[i-1]; i = i-1; } a[i] = key; } return a; } ListNode* createList(vector<int>a, int length) { ListNode * head, *tail, *mid; head = tail = NULL; int i = 0; while (i < length) { mid = new ListNode(-1); mid->val = a[i]; mid->next = NULL; if (head == NULL) { head = mid; } else { tail->next = mid; } tail = mid; i++; } return head; }};
0 0
- 排序3:插入排序(普通插入排序 + 折半插入排序 + 链表插入排序 + 希尔排序)
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 链表插入排序
- 如何在HTML网页中调起APP?
- Aggressive cows
- 元素居中使用margin:0 auto;为何没效果
- 主流开源流媒体服务器有哪些? FMS/RED5/WOWZA/SmartServer/NginxRtmp
- 开源大数据查询分析引擎现状
- 链表插入排序
- 成为专业程序员路上用到的各种优秀资料、神器及框架
- php-mac系统 环境变量设置
- Telephony之进程与实体
- Android极光推送集成和跳转
- Java 重要知识点
- 在真机上执行react-native run-android出现com.android.ddmlib.InstallException: Failed to finalize session错误
- Unity开发教程学习路线
- 【Mybatis】——初识架构