Leetcode_147_Insertion Sort Lis, sortlistleetcode

Source: Internet
Author: User

Leetcode_147_Insertion Sort Lis, sortlistleetcode

Thank you for your reference. If you have any errors or questions, please leave a message to correct them. Thank you.


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 5struct 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;}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.