本题实现链表的构造,采用表尾插入法构造链表,输出表中所有元素。
函数接口定义:
函数接口:
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
输出样例:
1 2 3
代码区:
ptr creat( )
{
struct node *p,*head,*tail;//头指针,尾指针
head=tail=NULL;
int x=-100;
while(scanf("%d",&x)&&x!=0)
{
//scanf("%d",&x);
p=(struct node*)malloc(sizeof(struct node));//动态内存分配申请数组空间
p->data = x;
p->next = NULL;
if(head == NULL){
head = tail = p;
}
else{
tail->next = p;
tail = p;
}
}
return head;
}
//构造链表
void output(ptr p)
{
//struct Node *p = head;
//printf("%d",p->data);
//p = p->next;
while(p){
printf("%d ",p->data);
p=p->next;
}
}//输出链表元素