[leetcode]Insertion Sort List
2014-05-14 19:40
281 查看
Insertion Sort List
Sort a linked list using insertion sort./** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(NULL == head) return NULL; ListNode *ptr = head->next, *q; ListNode *nhead = head; //新的头结点指针 ListNode *tptr = nhead; nhead->next = NULL; while(ptr){ q = ptr; ptr = ptr->next; if(q->val <= nhead->val){ //如果当前结点值 比头指针值还小 作为新的头指针 q->next = nhead; nhead = q; continue; } tptr = nhead; while(tptr->next){ //使用tptr->next是因为要记录前一结点的指针 if(tptr->next->val >= q->val) break; tptr = tptr->next; } q->next = tptr->next; tptr->next = q; } return nhead; } };
相关文章推荐
- LeetCode | Insertion Sort List(插入法排序链表)
- LeetCode (Insertion Sort List)
- [LeetCode] Insertion Sort List
- Insertion Sort List -- leetcode
- leetcode-Insertion Sort List
- [leetcode] Insertion Sort List
- 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]#147 Insertion Sort List
- leetcode-004 insertion sort list
- Leetcode-Insertion Sort List
- Insertion Sort List[LeetCode]
- Insertion Sort List | leetcode
- leetcode -- Insertion Sort List
- leetcode-Insertion Sort List
- LeetCode Insertion Sort List