leetcode-147. 对链表进行插入排序
题目:
代码:
#include <iostream>
#include <vector>
using namespace std;
typedef struct ListNode{
int val;
struct ListNode* next;
}ListNode,*LinkList;
ListNode* create(LinkList &head){
int n;
cin>>n;
head=new ListNode;
head->next=NULL;
ListNode *tail=head;
int tn;
for(int i=0;i<n;i++){
cin>>tn;
ListNode *p=new ListNode;
p->val=tn;
p->next=NULL;
tail->next=p;
tail=p;
}
return head->next;
}
ListNode* insertionSortList(ListNode* head) {
if(!head){
return head;
}
ListNode* h=new ListNode;
h->next=head;
ListNode* last=head;
ListNode* cur=head->next;
while(cur){
if(last->val<=cur->val){
last=last->next;
}else{
ListNode* pre=h;
while(pre->next->val<=cur->val){
pre=pre->next;
}
last->next=cur->next;
cur->next=pre->next;
pre->next=cur;
}
cur=last->next;
}
return h->next;
}
int main(){
ListNode* head;
create(head);
head=insertionSortList(head);
while(head){
cout<<head->val<<" ";
head=head->next;
}
return 0;
}