Leetcode-insertion-sort-list ***
来源:互联网 发布:多媒体互动教学软件 编辑:程序博客网 时间:2024/06/06 10:38
题目描述
Sort a linked list using insertion sort.
题目越短,事情越大。
用插入排序法对链表进行排序。
我是参考别人的解答做的,这题我不会。
* public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode insertionSortList(ListNode head) { if(head == null || head.next == null) return head; ListNode cursors = head; ListNode tempCur = null; ListNode temp = head; //待排序元素的上一个 元素 ListNode current = temp.next; //待排序元素 while(current != null){ if(current.val < head.val){ temp.next = current.next; //待排序元素上一个元素指向待排序元素下一个元素 current.next = head; head = current; }else{ // cursors-↓ ↓-temp // 1 -> 3 -> 5 -> 8 -> 4-> 12 -> 2 //tempCur-↑ current-↑ //插入后: // |-------有序---------| // 1 -> 3 -> 4 -> 5 -> 8-> 12 -> 2 //找到插入的位置 current插入到cursors的前面:temp->current->cursors tempCur = cursors; cursors = tempCur.next; while(cursors != current && cursors.val < current.val){ tempCur = cursors; cursors = cursors.next; } if(cursors == current){ temp = current; current = temp.next; }else{ temp.next = current.next; tempCur.next = current; current.next = cursors; } } cursors = head; current = temp.next; } return head; }}
数组的插入排序是从待排序元素往前找插入位置,而链表则是从头开始找插入位置。
0 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
- 最短路径树
- Word 2013自定义样式
- ARM代码的编译与链接调试
- Python *** 爬下糗事百科数据
- HashSet HashTable HashMap的区别
- Leetcode-insertion-sort-list ***
- 关于web前端面试题系列之必考面试题(面试官总结)
- 窄带信号和宽带信号的区别和联系
- java范型
- 判断一棵二叉树是否为对称的 java
- 访问Github失败,解决
- EL表达式
- centos下samba服务器的安装与配置
- SQL基本语法使用