leetcode:Insertion Sort List
2014-04-22 23:31
417 查看
这道题算法思路很简单,就是简单插入算法,但是由于是对链表的插入排序,所以对指针的操作比较容易出错,下面为我调试后通过的代码:
/** * 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==NULL || head->next==NULL) return head; ListNode *pre; ListNode *p=head; ListNode *ph=head; ListNode *pcur=head->next; p->next=NULL; ListNode *pnext=NULL; while(pcur!=NULL) { pnext=pcur->next; while(p!=NULL && p->val<=pcur->val) { pre=p; p=p->next; } if(p==ph) { pcur->next=p; ph=pcur; } else if(pre->next==NULL) //如果是else if(p==NULL)的话,条件判断语句好像不能判断该句,导致结果错误 { pre->next=pcur; pcur->next=NULL; } else { pre->next=pcur; pcur->next=p; } pcur=pnext; p=ph; } return ph; } };
相关文章推荐
- [LeetCode] Insertion Sort List
- LeetCode: Insertion Sort List [147]
- LeetCode :: Insertion Sort List [具体分析]
- (Leetcode 147)Insertion Sort List
- [leetcode] Insertion Sort List(python)
- Leetcode[147]-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 】 python 实现
- 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