6-7 表尾插入法构造链表
作者 唐艳琴
单位 中国人民解放军陆军工程大学
本题实现链表的构造,采用表尾插入法构造链表,输出表中所有元素。
函数接口定义:
函数接口:
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()
{
ptr head = (ptr)malloc(sizeof(snode));
ptr tail = head;
int x;
scanf("%d", &x);
while (x != 0) {
ptr node = (ptr)malloc(sizeof(snode));
node->data = x;
tail->next = node;
tail = node;
scanf("%d", &x);
}
tail->next = NULL;
return head;
}
void output(ptr p)
{
p = p->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}