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

时间:2023-03-09 15:37:18
九度OJ 1181:遍历链表 (链表、排序)

时间限制:1 秒

内存限制:32 兆

特殊判题:否

提交:2733

解决:1181

题目描述:

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

输入:

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

输出:

可能有多组测试数据,对于每组数据,

将n个整数建立升序链表,之后遍历链表并输出。

样例输入:
4
3 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
****************************************************************/