您的位置:首页 > 其它

[leetcode] Insertion Sort List

2014-07-07 09:44 267 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode