#include <stdio.h>
#include <stdlib.h>
struct node //结点数据类型
{
char data;
struct node *next;
};
void traverse(struct node* head);
void destroy(struct node* head);
struct node* headinsert(struct node* head);//该函数按照头插法,创建4个结点的动态链表,并返回第1个结点的地址
int main()
{
struct node *head=NULL;
head=headinsert(NULL); //用头插法创建链表
//遍历链表
traverse(head);
//释放资源,销毁链表中所有结点
destroy(head);
}
struct node* headinsert(struct node* head)
{
struct node *p;
char ch;
for (int i = 0; i < 4; i++)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%c", &ch);
p->data = ch;
p->next = head;
head = p;
}
return head;
}
void traverse(struct node* head)
{
struct node *p = head;
while (p!= NULL)
{
printf("%c ", p->data);
p = p->next;
}
printf("\n");
}
void destroy(struct node* head)
{
struct node *p = head;
while (p!= NULL)
{
struct node *q = p;
p = p->next;
free(q);
}
}