标签:
Sort a linked list using insertion sort.
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* insertionSortList(struct ListNode* head) { struct ListNode *p = head; struct ListNode *tmp = NULL, *min = NULL; int a; if(head == NULL) return NULL; else if(head->next == NULL) return head; while(p->next != NULL) { min = p; tmp = p->next; while(tmp != NULL) { if(tmp->val < min->val) min = tmp; tmp = tmp->next; } a = min->val; min->val = p->val; p->val = a; p = p->next; } return head; }
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* insertionSortList(struct ListNode* head) { struct ListNode *cur = head; struct ListNode *helper = malloc(sizeof(struct ListNode)); struct ListNode *pre; helper->next = NULL; if(head==NULL || head->next==NULL) return head; while(cur) { struct ListNode *next = cur->next; pre = helper; while(pre->next != NULL && pre->next->val < cur->val) pre = pre->next; cur->next = pre->next; pre->next = cur; cur = next; } return helper->next; }
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* insertionSortList(struct ListNode* head) { struct ListNode* new_head = malloc(sizeof(struct ListNode)); new_head -> next = head; struct ListNode* pre = new_head; struct ListNode* cur = head; while (cur) { if (cur -> next && cur -> next -> val < cur -> val) { while (pre -> next && pre -> next -> val < cur -> next -> val) pre = pre -> next; /* Insert cur -> next after pre.*/ struct ListNode* temp = pre -> next; pre -> next = cur -> next; cur -> next = cur -> next -> next; pre -> next -> next = temp; /* Move pre back to new_head. */ pre = new_head; } else cur = cur -> next; } struct ListNode* res = new_head -> next; free(new_head); return res; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/5020409.html