链表
什么是链表?链表是结构体变量与结构变量连接在一起
#include<stdio.h>
struct Node{
int data; //数据域
struct Node* next; //指针域
}
int main()
{
struct Node Node1 = { 1, NULL};
struct Node Node2 = { 2, NULL};
struct Node Node3 = { 3, NULL};
Node1.next = &Node2; //静态创建一个链表
Node2.next = &Node3;
system(pause)
return 0;
}
动态创建一个链表:动态内存申请+模块化设计
1、创建链表(创建一个表头表示整个链表)
2、创建节点
3、插入节点
4、删除节点
5、打印遍历链表(测试)
#include<stdio.h>
struct Node{
int data; //数据域
struct Node* next; //指针域
}
//创建链表
struct Node* creatList()
{
struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));
//headNode 成为了结构体变量
//变量使用前必须被初始化
headNode->next = NULL;
return headNode;
}
//创建节点
struct Node* newnode()
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
//变量使用前必须被初始化
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main()
{
struct Node* list = creatList();
system("pause");
return 0;
}
打印链表:
void printList(struct Node* headNode)
{
struct Node* pMove = headNode->next;
while(pMove)
{
printf("%d",pMove->data);
pMove = pMove->next;
}
printf("\n");
头部插入方式
//插入节点,参数:插入哪个链表,插入节点的数据是多少
void insertNodeByHead(struct Node* headNode,int data)
{
//1创建插入的节点
struct Node* newNode = creatNode(data);
newnode-> next = headNote->next;
headNote->next = newnode;
}
int main()
{
struct Node* list = creatList();
insertNodeByHead(list, 1);
insertNodeByHead(list, 2);
insertNodeByHead(list, 3);
printList(list);
system("pause");
return 0;
}
链表的删除:指定位置删除
void deleteNoteByAppoin(struct Node* headNode, int posData)
{
struct Node* posNode = headNode->next;
struct Node* posNodeFront = headNode;
if (posNode == NULL)
printf("无法删除链表为空\n");
else
{
while (posNode->data != posData)
{
posNodeFront = posNode;
posNode = posNodeFront->next;
if (posNode == NULL)
{
printf("没有找到相关信息,无法删除\n");
return;
}
}
}
}