标签:style blog color io strong div sp on c
题目描述:
Sort a linked list using insertion sort.
解决方案:
该题目就是用插入排序来对链表进行排序,很简单,直接上代码。
1 class Solution { 2 public: 3 ListNode *insertionSortList(ListNode *head) { 4 ListNode *q = head; 5 ListNode *temp = new ListNode(0); 6 temp->val = INT_MIN; 7 temp->next = NULL; 8 ListNode *p = temp; 9 ListNode * pre = NULL; 10 ListNode *k = NULL; 11 ListNode *f = NULL; 12 while (q != NULL) { 13 f = q; 14 q = q->next; 15 k = temp; 16 while(1) { 17 if (k == NULL) { 18 f->next = NULL; 19 pre->next = f; 20 break; 21 } 22 if (f->val < k->val) { 23 f->next = pre->next; 24 pre->next = f; 25 pre = k; 26 break; 27 } 28 pre = k; 29 k = k->next; 30 } 31 pre = NULL; 32 } 33 p = temp->next; 34 temp->next = NULL; 35 delete temp; 36 return p; 37 } 38 };
标签:style blog color io strong div sp on c
原文地址:http://www.cnblogs.com/skycore/p/3990827.html