LeetCode: Insertion Sort List [147]
2014-07-01 19:30
375 查看
【题目】
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* insert(ListNode*head, ListNode*node){ if(head==NULL){ node->next=NULL; return node; } ListNode*prev = NULL; ListNode*cur = head; while(cur){ if(cur->val>node->val){ //插入 if(prev==NULL){ //插到链表头 node->next=head; head = node; } else{ //插到链表中 node->next=prev->next; prev->next=node; } return head; } else{ prev=cur; cur=cur->next; } } //插到链表尾 prev->next=node; node->next=NULL; return head; } ListNode *insertionSortList(ListNode *head) { if(head==NULL || head->next==NULL)return head; ListNode*newhead=NULL; ListNode*cur=head; ListNode*next=NULL; while(cur){ next=cur->next; newhead=insert(newhead, cur); cur=next; } return newhead; } };
相关文章推荐
- [leetcode147]insertion sort list
- [Leetcode]#147 Insertion Sort List
- LeetCode(147) Insertion Sort List
- LeetCode147: Insertion Sort List
- leetcode-Insertion Sort List-147
- Leetcode 147 Insertion Sort List
- Java for LeetCode 147 Insertion Sort List
- LeetCode 147:Insertion Sort List
- leetcode 147 Insertion Sort List java 算法
- 【LEETCODE】147- Insertion Sort List [Python]
- leetcode[147]:Insertion Sort List
- [LeetCode]147 Insertion Sort List
- LeetCode 147 Insertion Sort List(链表)
- LeetCode147_Insertion Sort List(用插入排序算法对链表进行排序) Java题解
- [leetcode 147]Insertion Sort List
- LeetCode(147) Insertion Sort List
- LeetCode 147 Insertion Sort List
- leetcode_147 Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode(147) Insertion Sort List