Leetcode_Insertion Sort List
2014-02-17 15:18
387 查看
心得
这题调试了很久,要是笔试十分有可能写错,先做个笔记吧,应该还有更简短的写法题目
Sorta linked list using insertion sort.
思路
1、链表遍历模拟插入排序的两层循环,外层循环控制长度,内层循环控制查找应该插入的位置2、由于需要插入,故需要记录插入位置的前驱,同时特别要注意移动外层循环的指针
3、用了一点小技巧,用一个dump节点指向头,表示head的前驱
代码
class Solution { public: ListNode *insertionSortList(ListNode *head) { ListNode *p1,*p_pre,*q,*p2,*pre_p2,*q_pre; ListNode *dump = new ListNode(0); if(head==NULL || head->next==NULL ) return head; dump->next = head; pre_p2=head; p2 = head->next; p1= head; while(p2!=NULL) { q_pre=dump; q = dump->next; while(q!=p2 && q->val<p2->val) { q_pre = q; q = q->next; } if (q!=p2){//q->val>p2->value //first decompose pre_p2->next = p2->next; ListNode *temp = p2; p2 = p2->next; q_pre->next = temp; temp->next =q; }else { pre_p2 = p2; p2 = p2->next; } } return dump->next; } ListNode *input() { int x; ListNode *p,*head,*q; cin>>x; head = new ListNode(x); q=head; for (int i=1;i<2;i++) { cin>>x; p=new ListNode(x); q->next = p; q=q->next; } return head; } void output(ListNode *h) { while(h!=NULL){ cout<<h->val<<endl; h = h->next; } } };
相关文章推荐
- leetcode 名单 Insertion Sort List
- leetcode Insertion Sort List
- 和大神们学习每天一题(leetcode)-Insertion Sort List
- Leetcode -- Insertion Sort List
- leetcode 147 —— Insertion Sort List
- LeetCode Insertion Sort List
- leetcode147~Insertion Sort List
- LeetCode:Insertion Sort List
- [leetcode] Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode Insertion Sort List 链表插入排序
- LeetCode题目5:Insertion Sort List
- Insertion Sort List ---leetcode---Runtime Error
- leetcode insertionSortList
- [LeetCode]Insertion Sort List
- LeetCode -- Insertion Sort List
- leetcode[147]:Insertion Sort List
- LeetCode147_Insertion Sort List(用插入排序算法对链表进行排序) Java题解
- leetcode_147 Insertion Sort List
- LeetCode:Insertion Sort List