LeetCode | Insertion Sort List
2013-12-11 11:26
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 *insertionSortList(ListNode *head) { if(head==NULL) { return NULL; } else { ListNode* cur = head->next; head->next = NULL; while(cur!=NULL) { ListNode* p = head; if(cur->val < p->val) { head = cur; cur=cur->next; head->next=p; } else { while(p!=NULL) { if(p->next ==NULL) { p->next = cur; cur=cur->next; p->next->next = NULL; break; } else { if(cur->val < p->next->val) { ListNode* tmp = p->next; p->next = cur; cur=cur->next; p->next->next = tmp; break; } p=p->next; } } } } return head; } } };
更加简洁的一个版本:
/** * 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) { ListNode* p = head; ListNode* result = new ListNode(0); while(p != NULL){ ListNode* cur = p; p = p->next; insertSort(result, cur); } return result->next; } void insertSort(ListNode* head, ListNode* newNode){ while(head->next != NULL){ if(newNode->val < head->next->val){ newNode->next = head->next; head->next = newNode; return; } head = head->next; } if(head->next == NULL){ head->next = newNode; newNode->next = NULL; } } };
相关文章推荐
- LeetCode OJ 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] #147 Insertion Sort List
- [LeetCode]147 Insertion Sort List
- [leetcode] Insertion Sort List(python)
- LEETCODE: Insertion Sort List
- LeetCode ||Insertion Sort List
- leetcode Insertion Sort List
- Insertion Sort List —— LeetCode
- [Leetcode 147, medium] Insertion Sort List
- LeetCode(147) Insertion Sort List
- LeetCode:Insertion Sort List (Java)
- LeetCode—Insertion Sort List
- 【leetcode】Insertion Sort List
- leetcode 链表 Insertion Sort List