Leetcode -- Insertion Sort List
2015-08-16 21:19
441 查看
题目:
Sort a linked list using insertion sort.
分析:
插入排序。
代码1:
【参考代码:https://leetcode.com/discuss/24663/an-easy-and-clear-way-to-sort-o-1-space】
分析:
思路都是插入排序的思想。代码1比参考代码麻烦的原因是,每次好到插入的地方,就进行插入了。其实,只需要确定插入的地方,然后再进行插入就可以了。没有必要对插入地方进行分类。
其次就是比较的时候,等号的处理。代码1中,是需要考虑这个问题的。
Sort a linked list using insertion sort.
分析:
插入排序。
代码1:
/** * 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* l1 = head; ListNode* l1_next; ListNode* last = l1; ListNode* l2 = head->next; ListNode* l2_next; last -> next = NULL; l1->next = NULL; while(l2) { l1 = head; l2_next = l2->next; while(l1) { if(last->val <= l2->val) { last->next = l2; last = last->next; last->next = NULL; break; } if(l1->val > l2->val) { l2->next = l1; head = l2; break; } else { if(l1->val <= l2->val && l1->next && l1->next->val > l2->val) { l1_next = l1->next; l1->next = l2; l2->next = l1_next; break; } else { l1 = l1->next; } } } l2 = l2_next; } return head; } };
【参考代码:https://leetcode.com/discuss/24663/an-easy-and-clear-way-to-sort-o-1-space】
public ListNode insertionSortList(ListNode head) { if( head == null ){ return head; } ListNode helper = new ListNode(0); //new starter of the sorted list ListNode cur = head; //the node will be inserted ListNode pre = helper; //insert node between pre and pre.next ListNode next = null; //the next node will be inserted //not the end of input list while( cur != null ){ next = cur.next; //find the right place to insert while( pre.next != null && pre.next.val < cur.val ){ pre = pre.next; } //insert between pre and pre.next cur.next = pre.next; pre.next = cur; pre = helper; cur = next; } return helper.next; }
分析:
思路都是插入排序的思想。代码1比参考代码麻烦的原因是,每次好到插入的地方,就进行插入了。其实,只需要确定插入的地方,然后再进行插入就可以了。没有必要对插入地方进行分类。
其次就是比较的时候,等号的处理。代码1中,是需要考虑这个问题的。
相关文章推荐
- 插入排序
- php实现插入排序
- Java数据结构及算法实例:插入排序 Insertion Sort
- c++几种基本的插入排序(图文)
- Java排序算法总结之插入排序
- JAVA算法起步之插入排序实例
- java数组排序示例(冒泡排序、快速排序、希尔排序、选择排序)
- python插入排序算法的实现代码
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem