头插法
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkNode
{
int num;
LinkNode* next;
}Lk, * lk;
//初始化头节点
lk init_headNode()
{
//生成一个头节点
lk headNode = (lk)malloc(sizeof(Lk));
//检查分配空间是否成功
if (headNode == NULL)
{
return NULL;
}
//数据域可以不用维护
headNode->next = NULL;
return headNode;
}
//头插法
void insert_LinkList(lk headNode,int length)
{
//检查传入的头节点是否为空
if (headNode == NULL)
{
return ;
}
int val = 0;
int index = 0;
for (int i = 0; i < length; i++)
{
lk newNode = (lk)malloc(sizeof(Lk));
printf("请输入第%d个值:\n", (index++)+ 1);
scanf("%d", &val);
newNode->num = val;
newNode->next = NULL;
//下面两行代码不能反
newNode->next = headNode->next;
headNode->next = newNode;
}
}
//遍历链表
void outputLinkList(lk headNode)
{
if (headNode == NULL)
return;
//创建一个指针指向当前节点
lk curNode = headNode->next;
while (curNode)
{
printf("%d\n", curNode->num);
curNode = curNode->next;
}
}
int main()
{
lk headNode = init_headNode();
int length = 0;
printf("请输入所要输入的元素个数:\n");
scanf("%d", &length);
insert_LinkList(headNode,length);
printf("打印链表:\n");
outputLinkList(headNode);
return 0;
}
尾插法:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkNode
{
int num;
LinkNode* next;
}Lk, * lk;
//初始化头节点
lk init_headNode()
{
//生成一个头节点
lk headNode = (lk)malloc(sizeof(Lk));
//检查分配空间是否成功
if (headNode == NULL)
{
return NULL;
}
//数据域可以不用维护
headNode->next = NULL;
return headNode;
}
//尾插法
void insert_LinkList(lk headNode,int length)
{
//检查传入的头节点是否为空
if (headNode == NULL)
{
return ;
}
int val = 0;
int index = 0;
//创建一个尾指针,指向链表尾部,一开始头部即尾部
lk endNode = headNode;
for (int i = 0; i < length; i++)
{
printf("请输入第%d个数据:\n", (index++) + 1);
scanf("%d", &val);
lk newNode = (lk)malloc(sizeof(Lk));
newNode->num = val;
newNode->next = NULL;
//下面两行顺序不能反
endNode->next = newNode;
endNode = newNode;
}
//因为我们上面已经写了newNode->next=NULL
//因此下面这句话就可以不写
//当尾指针指向最后一个节点的时候,要将他的next指针置空,防止出现野指针
endNode->next = NULL;
}
//遍历链表
void outputLinkList(lk headNode)
{
if (headNode == NULL)
return;
//创建一个指针指向当前节点
lk curNode = headNode->next;
while (curNode)
{
printf("%d\n", curNode->num);
curNode = curNode->next;
}
}
int main()
{
lk headNode = init_headNode();
int length = 0;
printf("请输入所要输入的元素个数:\n");
scanf("%d", &length);
insert_LinkList(headNode,length);
printf("打印链表:\n");
outputLinkList(headNode);
return 0;
}