1.题目:
Problem Description
军训时,教官要求学生从低到高排成一列,可是由于你迟到了,教官要你根据自己的身高站到队列中,要求还是要从低到高排,所以你现在要找出自己的位置排到队列中!要求用链接存储结构实现。
Input
输入有多组数据:
每组数据第一行有一个正整数n,表示有n个人已排好了队;
第二行有n个数据表示队列;
第三行是你的身高x;
每组数据第一行有一个正整数n,表示有n个人已排好了队;
第二行有n个数据表示队列;
第三行是你的身高x;
Output
对于每组测试数据,输出有两行;
第一行输出你应该站的位置。
第二行输出插入后新的队列,数据之间用空格分隔。
第一行输出你应该站的位置。
第二行输出插入后新的队列,数据之间用空格分隔。
Sample Input
5
1 2 3 6 8
4
4
2 6 8 9
3
Sample Output
4
1 2 3 4 6 8
2
2 3 6 8 9
2.参考代码:
#include <iostream> using namespace std; struct Node{ int data; Node* next; }; class LinkList{ private: Node* head; public: LinkList(int* a,int n); ~LinkList(); void insert(int x); void show(); }; LinkList::LinkList(int* a,int n){ Node* r,* s; head=new Node; r=head; for(int i=0;i<n;i++){ s=new Node; s->data=a[i]; s->next=r->next; r->next=s; r=s; } r->next=NULL; } LinkList::~LinkList(){ Node* p,* q; p=head; while(p){ q=p; p=p->next; delete q; } } void LinkList::insert(int x){ ///核心代码 Node* p,* q,* s; q=head; p=q->next; int count=0; ///count是计数器 while(p && p->data<=x){ ///找到插入的位置 q=p; p=p->next; count++; } cout<<count+1<<endl; s=new Node; s->data=x; q->next=s; s->next=p; } void LinkList::show(){ Node* p; p=head->next; if(p){ cout<<p->data; p=p->next; while(p){ cout<<" "<<p->data; p=p->next; } cout<<endl; } } int main() { int n,i,x,a[111]; while(cin>>n){ for(i=0;i<n;i++) cin>>a[i]; LinkList w(a,n); cin>>x; w.insert(x); w.show(); } return 0; }