利用头插法,创建类似下图所示的动态链表,其中结点数据域由键盘输入而确定。要创建下图的链表,输入的依次是DCBA。
创建好链表后,还需要依次访问各个结点,输出各个结点的数据域。
输入
1行,4个字符
输出
4个字符,次序与输入相反,中间用空格分隔。
样例输入
XYUW
样例输出
W U Y X
#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* newnode;
char data;
for(int i=0;i<4;i++)
{
scanf("%c", &data);
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = head;
head = newnode;
}
return newnode;
}
void traverse(struct node* head) {
struct node* p;
p = head;
while (p!=NULL)
{
printf("%c ", p->data);
p=p->next;
}
}
void destroy(struct node* head) {
struct node* p;
struct node* k;
p = head;
while (p != NULL)
{
k = p;
p = p->next;
free(k);
}
}