[leetcode] Insertion Sort List

来源:互联网 发布:apache 负载压力测试 编辑:程序博客网 时间:2024/06/08 01:25

Sort a linked list using insertion sort.

思路:设立两个指针,当前指针和插入位置指针,当发现当前指针比插入位置值要小时,将两者的val交换,并且依次将插入位置指针的val往后推

输入示例:

4

4 3 2 1

代码参考了http://blog.csdn.net/doc_sgl/article/details/16343071

代码:

#include<iostream>using namespace std;struct ListNode{        int val;        ListNode *next;        ListNode(int x):val(x),next(NULL){}};ListNode *insertionSortList(ListNode *head){        if(head->next==NULL || head==NULL) return head;        ListNode *current=head->next;        ListNode *temp=NULL;        while(current!=NULL){                temp=head;                while(temp->val < current->val && temp != current){                        temp=temp->next;                }                if(temp!=current){                        int first=current->val;                        int second;                        while(temp!=current){                                second=temp->val;                                temp->val=first;                                first=second;                                temp=temp->next;                        }                        temp->val=first;                }                current=current->next;        }        return head;}int main(){        int n,a;        cin>>n;        ListNode *head,*p,*q;        head = (ListNode *)malloc(sizeof(ListNode));        q=head;        for(int i=0;i<n;i++){                cin>>a;                p=(ListNode *)malloc(sizeof(ListNode));                p->val=a;                q->next=p;                q=p;        }        q->next=NULL;        head=head->next;        ListNode *res=insertionSortList(head);        while(res!=NULL){                cout<<res->val<<" ";                res=res->next;        }        cout<<endl;        return 0;}


0 0