数据结构实验之链表六:有序链表的建立
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
输入
第一行输入整数个数N;
第二行输入N个无序的整数。
第二行输入N个无序的整数。
输出
依次输出有序链表的结点值。
示例输入
6 33 6 22 9 44 5
示例输出
5 6 9 22 33 44
代码
#include <iostream> using namespace std; struct node { int date; struct node *next; }; int main() { int i,n,t; struct node *head=NULL,*p=NULL,*q=NULL; cin>>n; head=new node; head->next=NULL; q=head; for(i=1;i<=n;i++) { p=new node; cin>>p->date; p->next=NULL; q->next=p; q=p; } q->next=NULL; q=head->next; while(q) { p=q; while(p) { if(p->date<q->date) { t=p->date;p->date=q->date;q->date=t; } else p=p->next; } q=q->next; } q=head->next; while(q) { cout<<q->date; if(q->next!=NULL) cout<<" "; else cout<<endl; q = q->next; } return 0; }