Insertion Sort List
Sort a linked list using insertion sort.
class Solution { public: ListNode *insertionSortList(ListNode *head) { if( head==NULL || head->next==NULL ) return head; ListNode *p = new ListNode(-1); p->next = head; ListNode *pre = head; ListNode *cur = head->next; while(cur) { if(cur->val>=pre->val) { pre = cur; cur = cur->next; } else { //first find the insert position ListNode *inserpre = p; ListNode *insercur = p->next; while( insercur->val < cur->val ) { inserpre = insercur; insercur = insercur->next; } pre->next = cur->next; cur->next = insercur; inserpre->next = cur; cur = pre->next; } } head = p->next; return head; } };
#include<iostream> #include<stack> using namespace std; #define N 5 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 = new ListNode(-1); p->next = head; ListNode *pre = head; ListNode *cur = head->next; while(cur) { if(cur->val>=pre->val) { pre = cur; cur = cur->next; } else { ListNode *inserpre = p; ListNode *insercur = p->next; while( insercur->val < cur->val ) { inserpre = insercur; insercur = insercur->next; } pre->next = cur->next; cur->next = insercur; inserpre->next = cur; cur = pre->next; } } head = p->next; return head; } }; ListNode *creatlist() { ListNode *head = NULL; ListNode *p; for(int i=0; i<N; i++) { int a; cin>>a; p = (ListNode*) malloc(sizeof(ListNode)); p->val = a; p->next = head; head = p; } return head; } int main() { ListNode *list = creatlist(); Solution lin; ListNode *outlist = lin.insertionSortList ( list ); for(int i=0; i<N; i++) { cout<<outlist->val; outlist = outlist->next; } }
leetcode_147_Insertion Sort Lis
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43833917