【Leetcode】Insertion Sort List
2014-06-02 10:57
330 查看
【题目】
Sort a linked list using insertion sort.
【代码】
【总结】:
1.对单链表使用插入排序算法:分成已排序链表和未排序链表,已排序链表初始值为链表head节点,顺序扫描单链表,插入到已排序好的链表中。
2.链表扫描过程中,要注意判空,复合条件判别式中,判空条件要放在最前面,否则对一个空指针进行其他操作是非法的
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) { if((NULL==head)||(NULL==head->next))return head; ListNode *result=head; ListNode *p=head->next; result->next=NULL; while(p){ ListNode *curNode=p; p=p->next; curNode->next=NULL; if(result->val>curNode->val){ curNode->next=result; result=curNode; continue; } ListNode *q=result,*pre=result; while(q&&(q->val<curNode->val)){ pre=q; q=q->next; } if(pre)curNode->next=pre->next; pre->next=curNode; } return result; } };
【总结】:
1.对单链表使用插入排序算法:分成已排序链表和未排序链表,已排序链表初始值为链表head节点,顺序扫描单链表,插入到已排序好的链表中。
2.链表扫描过程中,要注意判空,复合条件判别式中,判空条件要放在最前面,否则对一个空指针进行其他操作是非法的
相关文章推荐
- LeetCode Insertion Sort List
- The Solution to LeetCode 147 Insertion Sort List
- [LeetCode]Insertion Sort List
- Leetcode: Insertion Sort List
- LeetCode:Insertion Sort List
- Leetcode[147]-Insertion Sort List
- LeetCode题目5:Insertion Sort List
- Insertion Sort List ---leetcode---Runtime Error
- LeetCode 147:Insertion Sort List
- Leetcode---Insertion Sort List
- [LeetCode-Algorithms-147] "Insertion Sort List" (2017.12.21-WEEK16)
- 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 (Java)