九度oj题目1181:遍历链表

题目1181:遍历链表

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:2600

解决:1125

题目描述:

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

输入:

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

输出:

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

样例输入:
4
3 5 7 9
样例输出:
3 5 7 9
来源:
2000年华中科技大学计算机研究生机试真题

链表排序

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <string>
 4 #include <queue>
 5 #include <stack>
 6 #include <iostream>
 7 using namespace std;
 8 struct node{
 9     int v;
10     node *next;
11 };
12 int main(){
13     //freopen("D:\INPUT.txt","r",stdin);
14     int n;
15     node *head;
16     while(scanf("%d",&n)!=EOF){
17         head=new node();
18         //head->v=
19         head->next=NULL;
20         int i,num;
21         node *p,*q;
22         for(i=0;i<n;i++){
23             scanf("%d",&num);
24             q=head;
25             p=head->next;
26             while(p&&num>=p->v){
27                 q=p;
28                 p=p->next;
29             }
30             node *t=new node();
31             t->v=num;
32             q->next=t;
33             t->next=p;
34         }
35         p=head->next;
36         cout<<p->v;
37         p=p->next;
38         while(p){
39             cout<<" "<<p->v;
40             p=p->next;
41         }
42         cout<<endl;
43     }
44     return 0;
45 }
原文地址:https://www.cnblogs.com/Deribs4/p/4649833.html