c语言链表的实现
作者:
Aqiw
,
2025-04-16 13:18:37
· 河北
,
所有人可见
,
阅读 2
c语言链表的实现
#include<stdio.h>
#include<stdlib.h>
struct node
{
char name[20];
int age;
struct node *next;
};
int main()
{
struct node *p,*head,*tail;
head=(struct node*)malloc(sizeof(node));
if(head==NULL)
{
printf("内存分配失败\n");
return 1;
}
tail=head;
tail->next=NULL;
for(int i=0;i<3;i++)
{
p=(struct node*)malloc(sizeof(node));
if(p==NULL)
{
printf("内存分配失败\n");
return 1;
}
printf("请输入姓名:");
scanf("%s",p->name);
printf("请输入年龄:");
scanf("%d",&p->age);
tail->next=p;
tail=p;
tail->next=NULL;
}
p=head->next;
while(p!=NULL)
{
printf("姓名:%s 年龄:%d\n",p->name,p->age);
p=p->next;
}
p=head;
while(p!=NULL)
{
struct node *temp=p;
p=p->next;
free(temp);
}
return 0;
}