题目:
使用头插入法创建单链表
实现输入数字倒序输出
源代码:
#include <stdio.h>
#include <stdlib.h>
struct DATA
{
int num;
};
struct NODE
{
struct DATA data;
struct NODE * next;
};
struct HEAD
{
struct NODE * first;
};
void initialization(struct HEAD * head);
void create_node(struct HEAD * head,int num);
void node_print(struct HEAD * head);
int main()
{
struct HEAD head;
int num;
initialization(&head);
printf("请输入你要插入的数字: ");
while((num = getchar()) && num != 10)
{
create_node(&head,num-48);
if((num = getchar()) && num == 10) ungetc(num,stdin);
}
printf("结果是: ");
node_print(&head);
return 0;
}
void initialization(struct HEAD * head)
{
head->first = (struct NODE *) malloc (sizeof(struct NODE));
head->first->next= NULL;
}
void create_node(struct HEAD * head,int num)
{
struct NODE * tmp_pointer = (struct NODE *) malloc (sizeof(struct NODE));
tmp_pointer->data.num = num;
tmp_pointer->next = NULL;
if(head->first->next == NULL)
{
head->first->next = tmp_pointer;
}
else
{
tmp_pointer->next = head->first->next;
head->first->next = tmp_pointer;
}
}
void node_print(struct HEAD * head)
{
struct NODE * pointer = head->first->next;
while(pointer != NULL)
{
printf("%d ",pointer->data.num);
pointer = pointer->next;
}
}
演示效果:
如果朋友你感觉文章的内容对你有帮助,可以点赞,关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈