一、单链表关键
定义一个结构体用于储存数据,结构体中存在一个指针(指针类型与结构体类型一致)用于指向下一个节点。
二、单链表增删查改的关键
遍历节点,找到目标节点指针,进行增删查改的操作
三、代码实现
#include "stdio.h"
#include "stdlib.h"//malloc和free函数所在的库;
typedef struct node{
char name;
int phone_number;
struct node *next;
}node;
//////////////////////////////////////////////////定义节点;
node *search(node *head,int n)
{
node *result=head ;//从头节点开始遍历查找;
for(int i=0;i<n;i++){
result=result->next ;//更新节点地址;
}
return result;//返回目标节点的地址;
}
//////////////////////////////////////////////////链表查找;
void increase_node(node *head_node,char Name,int phonenumber)
{
node *new_node=(node *)malloc(sizeof(node));
node *judge=head_node;//从头节点开始找到最尾部的节点;
while(judge->next !=NULL){
judge=judge->next ;//更新节点;
}//遍历查找尾部节点;
judge->next =new_node;//将最尾部的节点指向新节点;
new_node->name =Name;
new_node->phone_number =phonenumber;//将数据写入新节点;
new_node->next =NULL;//将新节点指向空;
}
////////////////////////////////////////////////新增链表;
void insert(node *head,char Name,int phonenumber,int target)
{
node *p=(node*)malloc(sizeof(node));//为新节点分配内存;
p->next =search(head,target);//使插入节点指向下一个节点;
node *tar=(search(head,target-1));//找到目标位置的前一个节点;
tar->next =p;//将前一个节点指向新节点;
p->name =Name;
p->phone_number =phonenumber;//写入新节点数据;
}
/////////////////////////////////////////////////链表插入;
void delet(node *head,int target)
{
node *ahead=search(head,target-1);//找到前一节点;
node *targ=search(head,target);//找到目标节点;
ahead->next =search(head,target+1);//将目标节点前一个节点指向下一个节点;
free(targ);//释放目标节点内存;
}
//////////////////////////////////////////////删除目标节点;
void change(node *head,char Name,int phonenumber,int target)
{
node *targ=search(head,target);//找到目标节点;
targ->name =Name;
targ->phone_number =phonenumber;//写入新数据;
}
//////////////////////////////////////////////修改节点数据;
int main(void){
node *head=(node*)malloc(sizeof(node));
head->next =NULL;//创建头节点;
increase_node(head,'A',123456);
increase_node(head,'B',123456);//新建节点,写入数据;
insert(head,'C',123456,2);//插入节点
delet(head,2); //删除目标节点
node *target=search(head,2);//查找链表;
printf("%c %d",target->name ,target->phone_number );
return 0;
}