数据结构实验之链表六:有序链表的建立
Description
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
Input
第一行输入整数个数N;
第二行输入N个无序的整数。
Output
依次输出有序链表的结点值。
Samples
Sample #1
Input
6
33 6 22 9 44 5
Output
5 6 9 22 33 44
分析:
插入时主要需要找前驱,写的有点麻烦,步骤应该能继续简化
#include <bits/stdc++.h>
using namespace std;
typedef struct node{
int data;
struct node *next;
}s;
int n,m,x,k=0;
int main(){
cin>>n;
int a;
s *head,*p,*q,*r,*t;
head=(struct node *)malloc (sizeof(struct node));
p=(struct node *)malloc (sizeof(struct node));
s *tail=head;
cin>>a;
p->data=a;
head->next=p;
p->next=NULL;
for(int i=1;i<n;i++){
cin>>a;
r=head;
q=head->next;
while(a>q->data&&q->next!=NULL){
q=q->next;
r=r->next;
}
t=(struct node *)malloc (sizeof(struct node));
t->data=a;
if(q->next==NULL){
if(q->data<a){
q->next=t;
t->next=NULL;
}
else{
t->next=q;
r->next=t;
}
}
else{
t->next=q;
r->next=t;
}
}
p=head->next;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return 0;
}