《leetCode》:Insertion Sort List
来源:互联网 发布:赵薇杀人知乎 编辑:程序博客网 时间:2024/06/04 19:30
题目
Sort a linked list using insertion sort.
思路
原以为可以直接在链表上利用插入排序来进行,单尝试了半天发现在链表上直接用插入排序有点困难,不可行,因此,就决定将链表中的val保存到一个数组中,然后对数组中的元素进行插入排序,最后进行链表的构建。
说到上面的思路,就有一个关于leetcode关于这个题目是怎么测试的,怎么测试我们有没有用到快排呢???
实现代码如下:
struct ListNode { int val; struct ListNode *next;};void insertsortArray(int *nums,int numsSize){ if(nums==NULL||numsSize<=1){ return; } for(int i=1;i<numsSize;i++){ int temp=nums[i]; int j=i-1; for(;j>=0;j--){ if(temp<nums[j]){ nums[j+1]=nums[j]; } else if(nums[j]<=temp){ nums[j+1]=temp; break; } } if(j<0){ nums[0]=temp; } }}#define N 100000struct ListNode* insertionSortList(struct ListNode* head) { if(head==NULL||head->next==NULL){ return head; } int *value=(int *)malloc(N*sizeof(int)); if(value==NULL){ exit(EXIT_FAILURE); } struct ListNode* cur=head; int index=0; while(cur!=NULL){ value[index++]=cur->val; cur=cur->next; } //对数组进行插入排序 insertsortArray(value,index); //重组为链表 head->val=value[0]; head->next=NULL; struct ListNode *curNode=head; struct ListNode* node=NULL; for(int i=1;i<index;i++){ node=(struct ListNode*)malloc(sizeof(struct ListNode)); if(node==NULL){ exit(EXIT_FAILURE); } node->val=value[i]; node->next=NULL;//注意:这里要设为NULL,否则不能AC,这个bug卡了我好久 curNode->next=node; curNode=node; } return head; }
1 0
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List (LeetCode)
- [LeetCode] Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode Insertion Sort List
- Insertion Sort List -- LeetCode
- Insertion Sort List (LeetCode)
- LeetCode Insertion Sort List
- leetcode Insertion Sort List
- 深入理解Android之AOP
- Leetcode: 232. Implement Queue using Stacks(JAVA)
- 机器学习中的相似性度量
- 不谈程序,谈发展,推荐一些励志书,也许可以改变你的困境
- traits编程技法感悟
- 《leetCode》:Insertion Sort List
- 《linux设备驱动程序》前期准备工作
- HDU 1686 Oulipo(KMP)
- 将Eclipse代码导入到AndroidStudio的两种方式
- 蓝桥杯 算法训练 最短路 (链式前向星,spfa)
- android .9图片使用和一些技巧
- Python 字典中包含中文的输出
- 基本的Linux命令
- JAVA正则表达式 Pattern和Matcher