#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct List
{
int number;
char name[MAX];
struct List *next;
};
typedef struct List Node;
typedef Node *Link;
/*********************
* 释放链表
********************/
void free_list(Link head)
{
Link pointer;
while(head != NULL)
{
pointer = head;
head = head->next;
free(pointer);
}
}
/*********************
* 输出链表
********************/
void print_list(Link head)
{
Link pointer; //节点声明
pointer = head; //将pointer节点设为首节点
while(pointer != NULL)
{
printf("Data number = %d\n", pointer->number);
printf("Data name = %s\n", pointer->name);
pointer = pointer->next;
}
}
/*********************
* 建立链表
*********************/
Link create_list(Link head)
{
int datanum;
char dataname[MAX];
Link new;
Link pointer;
int i;
head = (Link)malloc(sizeof(Node));
if(head == NULL)
{
printf("memory allocate failure!\n");
}
else
{
datanum = 1;
printf("please input the dataname: ");
scanf("%s", dataname);
head->number = datanum; //定义首节点数据
for(i = 0; i < MAX; ++i)
{
head->name[i] = dataname[i];
}
head->next = NULL;
pointer = head; //pointer 指针为首节点
while(1)
{
datanum++;
new = (Link)malloc(sizeof(Node));
printf("please input the dataname: ");
scanf("%s", dataname);
if(dataname[0] == '0') //输入0则结束
break;
new->number = datanum;
for(i = 0; i < MAX; ++i)
{
new->name[i] = dataname[i];
}
new->next = NULL;
pointer->next = new; //将新节点串联在链表尾端
pointer = new; //链表尾端节点为新节点
}
}
return head;
}
int main()
{
Link head; //声明节点
head = create_list(head);
if(head != NULL)
{
print_list(head);
free_list(head);
}
return 0;
}
C语言:单链表的创建,打印及销毁
最新推荐文章于 2024-07-17 15:34:39 发布