链表概念:
链表使用说明:
画图示意:
静态链表
代码语言:javascript复制#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
typedef struct LinkNode
{
int num;
LinkNode* next;
}Lk,*lk;
//Lk ------>struct LinkNode
//lk----->struct LinkNode*
void test01()
{
//静态链表
//Lk ------>struct LinkNode
Lk node1 = {10,NULL};
Lk node2 = { 20,NULL };
Lk node3 = { 30,NULL };
Lk node4 = { 40,NULL };
Lk node5 = { 50,NULL };
//建立关系
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
node4.next = &node5;
node5.next = NULL;
//lk----->struct LinkNode*
lk nodeCurrent = &node1;
//遍历输出
while (nodeCurrent)
{
printf("%dn", nodeCurrent->num);
nodeCurrent = nodeCurrent->next;
}
}
int main()
{
test01();
return 0;
}
动态链表
代码语言:javascript复制#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkNode
{
int num;
LinkNode* next;
}Lk,*lk;
//Lk ------>struct LinkNode
//lk----->struct LinkNode*
void test01()
{
//动态链表
lk node1 = (lk)malloc(sizeof(Lk));
lk node2 = (lk)malloc(sizeof(Lk));
lk node3 = (lk)malloc(sizeof(Lk));
lk node4 = (lk)malloc(sizeof(Lk));
lk node5 = (lk)malloc(sizeof(Lk));
//给数据赋值
node1->num = 10;
node2->num = 20;
node3->num = 30;
node4->num = 40;
node5->num = 50;
//建立联系
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
node5->next = NULL;
//lk----->struct LinkNode*
lk nodeCurrent = node1;
//遍历输出
while (nodeCurrent)
{
printf("%dn", nodeCurrent->num);
nodeCurrent = nodeCurrent->next;
}
//释放堆区开辟内存
free(node1);
free(node2);
free(node3);
free(node4);
free(node5);
//防止野指针出现
node1 = NULL;
node2 = NULL;
node3 = NULL;
node4 = NULL;
node5 = NULL;
}
int main()
{
test01();
return 0;
}