创建一个链表并且一直往头部插入字节,思维如下
具体实现方法就是,创建完一个链表,然后一直创建新的节点插入到头节点,如果头节点为空,则直接插入,如果不为空,则新创建的头节点的地址域指向上一头节点,具体实现的代码如下
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
/*创建一个链表结构体*/
struct Node
{
int data;//数据域
struct Node* next;//地址域
};
/*显示和插入函数*/
void Print(struct Node *head);
void InsertHead(struct Node **head, int x);
int main()
{
struct Node * Head=NULL;//创建头节点
int count=0,num=0;//创建2个变量表示要输入数据的个数和数据
printf("请输入要输入数据的个数:");
scanf("%d", &count);
printf("\n");
while (count--)
{
printf("要插入头部的数据:");
scanf("%d", &num);
/*需要输入的Head为最新的头节点*/
InsertHead(&Head,num);
Print(Head);
}
return 0;
}
void Print(struct Node *head)
{
printf("当前链表:");
while (head != NULL)//未达到尾结点
{
printf(" %d", head->data);
head = head->next;
}
printf("\n");
}
void InsertHead(struct Node **head,int x)
{
struct Node * temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
/*链表为空,插入节点为第一个节点 head=NULL
**链表不为 插入节点的地址域指向的head为上一不为NULL的头部节点
*/
temp->next = *head;
*head = temp;//插入的节点为新的头节点
}