[Leetcode]#147 Insertion Sort List
2015-09-02 07:45
302 查看
//#147 Insertion Sort List //80ms 81.07% #include <iostream> using namespace std; /** * 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) //"insertion sort" { if(head == NULL || head->next == NULL) return head; //after this point, all in coming linked lists have a size of 2 or more ListNode *p, *next_p, *n; //ListNode *end, //end = head; p = head->next; next_p = p->next; head->next = NULL; //end->next = NULL; while(p != NULL) { //cout << "L0 "; p->next = NULL; if(head->val > p->val) { p->next = head; head = p; } else { n = head; while(n->next != NULL) { //cout << "L1 "; if(n->next->val > p->val) { p->next = n->next; n->next = p; break; } n = n->next; } n->next = p; } //insertion finished //prepare for next item p = next_p; if(next_p != NULL) { next_p = next_p->next; } //list_print(head); } return head; } };
相关文章推荐
- 解析Java中的队列和用LinkedList集合模拟队列的方法
- JAVA LinkedList和ArrayList的使用及性能分析
- LinkedList学习示例模拟堆栈与队列数据结构
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- ArrayList和LinkedList的主要区别
- [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
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解