九度OJ 1181:遍历链表 (链表、排序)

来源:互联网 发布:java中的restfull接口 编辑:程序博客网 时间:2024/05/16 18:03

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:2733

解决:1181

题目描述:

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

输入:

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

输出:

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

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

代码:

#include <stdio.h>#include <stdlib.h> #define N 1000 struct node {    int key;    struct node *next;}; struct node *insert(struct node *head, int key){    if (head == NULL)    {        head = (struct node *)malloc(sizeof(struct node));        head->key = key;        head->next = NULL;        return head;    }    struct node *p = head, *p0;    p0 = p;    while (p && p->key < key)    {        p0 = p;        p = p->next;    }    struct node *pnew = (struct node *)malloc(sizeof(struct node));    pnew->key = key;    pnew->next = p;    if (p == head)        return pnew;    p0->next = pnew;    return head;} int main(void){    int n, i, key;    struct node *head;     while (scanf("%d", &n) != EOF)    {        head = NULL;        for(i=0; i<n; i++)        {            scanf("%d", &key);            head = insert(head, key);        }        printf("%d", head->key);        head = head->next;        while (head)        {            printf(" %d", head->key);            head = head->next;        }        printf("\n");    }     return 0;}/**************************************************************    Problem: 1181    User: liangrx06    Language: C    Result: Accepted    Time:170 ms    Memory:6192 kb****************************************************************/


0 0