2000年华中科技大学计算机研究生机试真题 遍历链表

题目1181:遍历链表

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:2570

解决:1113

题目描述:

建立一个升序链表并遍历输出。

输入:

输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。

输出:

可能有多组测试数据,对于每组数据,
将n个整数建立升序链表,之后遍历链表并输出。

样例输入:
4
3 5 7 9
样例输出:
3 5 7 9
来源:
2000年华中科技大学计算机研究生机试真题
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 struct node{
 6     int v;
 7     node *next;
 8     node(){}
 9     node(int a){
10         v=a;
11         next=NULL;
12     }
13 };
14 int main(){
15     int n;
16     while(cin>>n){
17     node *first=new node();
18     first->v=-1;
19     first->next=NULL;
20     int num;
21     while(n--){
22         node *p=first,*pp=p;
23         scanf("%d",&num);
24         while(p&&num>p->v){
25             pp=p;
26             p=p->next;
27         }
28         node *q=new node(num);
29         q->next=p;
30         pp->next=q;
31     }
32     node *p=first->next;
33     if(p){
34         cout<<p->v;
35         p=p->next;
36     }
37     while(p){
38         cout<<" "<<p->v;
39         p=p->next;
40     }
41     cout<<endl;
42     }
43     return 0;
44 }
原文地址:https://www.cnblogs.com/Deribs4/p/4599053.html