【leetcode】Insertion Sort List
2015-05-17 20:31
267 查看
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) { if(head==NULL || head->next==NULL) return head; ListNode *p,*q; p=head; q=head->next; while(q) { if(q->val<p->val) { ListNode *innerp,*innerq; innerp=head; innerq=head->next; while(q->val>innerq->val) { innerp=innerp->next; innerq=innerq->next; } if(innerp==head && innerp->val > q->val) { p->next=q->next; q->next=head; head=q; } else { p->next=q->next; innerp->next=q; q->next=innerq; } q=p->next; } else { p=p->next; q=q->next; } } return head; } };
相关文章推荐
- (leetcode)Insertion Sort List
- [Leetcode] insertion sort list 链表插入排序
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- Insertion Sort List (LeetCode)
- [Leetcode Solution]Insertion Sort List
- leetcode[147]Insertion Sort List
- [Leetcode] Insertion Sort List
- Insertion Sort List 【leetcode】
- leetcode Insertion Sort List(*)
- [leetcode 147] Insertion Sort List
- leetcode-Insertion Sort List-147
- 【LeetCode】Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode_Insertion Sort List
- 59_leetcode_Insertion Sort List
- LeetCode——Insertion Sort List
- 【LeetCode with Python】 Insertion Sort List
- LeetCode:Insertion Sort List
- leetcode之insertion Sort list