本题实现链表的构造,采用表头插入法构造链表,输出表中所有元素。
函数接口定义:
函数接口:
ptr creat( );//构造链表
void output(ptr p);//输出链表元素
其中 p
是用户传入的参数。creat函数返回链表的头指针,输入在creat函数中输入,以0表示输入结束。output函数输出链表元素,以一个空格隔开。
裁判测试程序样例:
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node *next;
}snode,*ptr;
ptr creat( );//构造链表
void output(ptr p);//输出链表元素
int main()
{
ptr head;
head=creat();
output(head);
return 0;
}
/* 请在这里填写答案 */
输入样例:
1 2 3 0
输出样例:
3 2 1
代码实现:
ptr creat()
{
int x;
ptr head,p;
head=NULL;
scanf("%d",&x);
while(x!=0)
{
p=(ptr)malloc(sizeof(snode));
p->data=x;
p->next=head;
head=p;
scanf("%d",&x);
}
return head;
}
void output(ptr p)
{
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}