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 行中输出当前链表,数字之间用空格隔开,行尾没有多余的空格。
Sample Input
3 5
1 2 3
5
0
4
0
9
Sample Output
5 1 2 3
4 5 1 2 3
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
struct node *creat(int N)
{
struct node *tail,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
while(N)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
N--;
}
return head;
}
void print(struct node *head)
{
struct node *p;
p=head->next;
while(p!=NULL)
{
printf("%d",p->data);
if(p->next!=NULL)
{
printf(" ");
}
else
{
printf("\n");
}
p=p->next;
}
}
void insert(int v)
{
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
p->data=v;
p->next=head->next;
head->next=p;
}
int main()
{
int n,m,v;
while(scanf("%d %d",&n,&m)!=EOF)
{
head=creat(n);
while(m)
{
scanf("%d",&v);
if(v!=0)
{
insert(v);
}
else
{
print(head);
}
m--;
}
}
return 0;
}