Insertion Sort List
2014-02-19 23:40
295 查看
Sort a linked list using insertion sort.
思路比较简单,就是用 insertion sort 的方法套用到 liked list 上。
一个新的node添加到队头的情况用 dummy head 可以方便地解决。
添加到队尾的情况就是对应于 (n == null),说明需要添加到队尾
public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) { return head; } // usding dummy head to simplify ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode curt = head.next; head.next = null; while (curt != null) { ListNode nodeToInsert = curt; curt = curt.next; nodeToInsert.next = null; // iterate sort list ListNode prev = dummyHead; ListNode n = dummyHead.next; while (n != null) { if (nodeToInsert.val <= n.val) { prev.next = nodeToInsert; nodeToInsert.next = n; break; } else { prev = n; n = n.next; } } // 之前都没有比上,一直到 n == null // attach 到 sort list 队尾 if (n == null) { prev.next = nodeToInsert; } } return dummyHead.next; }
思路比较简单,就是用 insertion sort 的方法套用到 liked list 上。
一个新的node添加到队头的情况用 dummy head 可以方便地解决。
添加到队尾的情况就是对应于 (n == null),说明需要添加到队尾
相关文章推荐
- 链表插入排序(insertion-sort-list)
- LeetCode: Insertion Sort List
- Sort a linked list using insertion sort
- Insertion Sort List
- [LeetCode#147]Insertion Sort List
- LeetCode---Insertion Sort List
- Insertion Sort List
- LeetCode:Insertion Sort List
- Foundation Sorting: Single List Insertion Sort
- Insertion Sort List
- LeetCode 147 Insertion Sort List
- Insertion Sort List
- [LeetCode]Insertion Sort List
- [leetcode] Insertion Sort List
- Insertion Sort List
- LeetCode_Insertion Sort List
- [leetcode] Insertion Sort List
- [LeetCode]题解(python):147-Insertion Sort List
- Insertion Sort List
- LeetCode题解:Insertion Sort List