玩链表
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
bLue 获得了一个含有 n 个数的初始链表,现在他要把另外的一些数插入到链表的开头。你能帮他完成吗?
Input
输入数据有多组(数据组数不超过 20),到 EOF 结束。
对于每组数据:
- 第 1 行输入 2 个整数 n (1 <= n <= 50000) 和 m (1 <= m <= 10000),分别表示初始链表中元素的个数和要进行的操作次数
- 第 2 行输入 n 个用空格隔开的整数 ai (1 <= ai <= 1000),表示初始链表
- 接下来 m 行,每行输入 1 个整数 v (0 <= v <= 1000),如果 v 不为 0,则将 v 插入到链表的最前面;如果 v 为 0,则输出当前链表
Output
对于每组数据中的每次输出操作,在 1 行中输出当前链表,数字之间用空格隔开,行尾没有多余的空格。
Example Input
3 5 1 2 3 5 0 4 0 9
Example Output
5 1 2 3 4 5 1 2 3
Hint
Author
【2016级《程序设计基础(B)II》期末上机考试-补测】bLue
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; int main() { int n,m,i,j,num; while(scanf("%d%d",&n,&m) != EOF) { struct node *head,*tail,*p; head = (struct node *)malloc(sizeof(struct node)); head -> next = NULL; tail = head; for(i = 0; i <n;i++) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d",&p->data); p->next=NULL; tail->next = p; tail = p; } for(i = 0;i < m;i++) { scanf("%d",&num); if(num == 0) { for(p=head->next;p->next!=NULL;p = p->next) { printf("%d ",p->data); } printf("%d\n",p->data); } else { p = (struct node *)malloc(sizeof(struct node)); p->data = num; p->next = head->next; head->next = p; } } } return 0; }