遍历链表

来源:互联网 发布:apache 禁止目录 编辑:程序博客网 时间:2024/06/15 22:36
题目描述:

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

输入:

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

输出:

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

样例输入:
43 5 7 9
样例输出:
3 5 7 9
来源:
2000年华中科技大学计算机研究生机试真题
#include<stdio.h>#include<malloc.h>typedef struct Node //存储节点信息{    int data;    struct Node *next;} linklist;int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        linklist *head,*p,*pre,*newNode  ;        head=(linklist*)malloc(sizeof(linklist));        head->next=NULL;        for(int i=0; i<n; i++) //构建链表        {            newNode=(linklist*)malloc(sizeof(linklist));            scanf("%d",&newNode->data);            p=head->next;            pre=head;            while(p)            {                if(newNode->data<p->data)                {                    break;                }                pre=p;                p=p->next;            }            newNode->next=p;            pre->next=newNode;        }        //输出        p=head->next;        printf("%d ",p->data);        while(p->next)        {            p=p->next;            printf("%d ",p->data);        }        printf("\n");    }    return 0;}