什么是链表?
链表是结构体变量与结构体变量通过指针连接在一起。
创建静态链表:
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={1,null};
Node1.next=&Node2;
Node2.next=&Node3;
return 0;
}
动态创建一个链表:动态内存申请+模块化设计
1、创建链表(创建一个表头表示整个链表)
2、创建节点
3、插入结点
4、删除节点
5、打印遍历链表(测试)
1、创建动态链表
struct Node{
int data;
struct Node *next;
};
struct Node* createList()
{
struct Node* headNode=(struct Node*)(malloc(sizeof(struct Node)));
//headNode成为了结构体变量,变量使用前必须初始化
//headNode->data=1;
headNode->next=NULL;
}
2、创建结点
//创建结点
struct Node *createNode(int data)
{
struct Node* newNode=(struct Node*)(malloc(sizeof(struct Node)));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
3、插入节点(头插法)
//插入结点,参数:插入哪个链表,插入节点的数据是多少
void insertNodeByHead(struct Node* headNode,int data)
{
struct Node* newNode=createNode(data);
newNode->next=headNode->next;
headNode->next=newNode;
}
4、删除节点
//删除节点
void deleteNodeByAppoin(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;
}
}
posNodeFront->next=posNode->next;
free(posNode);
}
}
5、打印节点
//打印链表
void printList(struct Node* headNode)
{
struct Node* pMove;
while(pMove){
printf("%d",pMove->data);
pMove=pMove->next;
}
printf("\n");
}