66.
编程题
⑴ 创建一个链表,每个链表结点包括2个成员:1个整数和1个next指针,要求每个节点的整数成员从键盘输入整数值,当输入0表示数据输入结束;
⑵ 输出链表中每个结点的数据成员的值。
要求使用typedef机制给结点的结构体类型起一个简短的类型名字,并使用这个短类型名来定义变量。
请认真测试程序的正确性。将源代码以文本方式提交,不要直接提交文件。
#include<stdio.h>
#include<string.h>
#include<conio.h>
typedef struct student{
int data;
struct student *next;
} node;
//创建链表
node *creat(){
node *head,*p,*s;
int x,cycle=1;
head =(node *)malloc(sizeof(node));
p=head;
while(cycle){
cin >>x;
if(x!=0){
s=(node *)malloc(sizeof(node));
s->data=x;
p->next=s;
p=s;
}else cycle=0;
}
head=head->next;
p->next=NULL;
return head;
}
//求链表长度
int lengthNode(node *head){
int n=0;
node *p;
p=head;
while(p!=NULL){
p=p->next;
n++;
}
return n;
}
//打印链表
void printNode(node *head){
node *p;
int n;
n=lengthNode(head);
p=head;
if(head!=NULL){
while(p!=NULL){
printf("%d ", p->data)';
p=p->next;
}
}
}
//主函数
int main(){
node *head=NULL;
head=creat();
printNode(head);
return 0;
}