#include<stdio.h>
#include"list.h"
#include<stdlib.h>
#include<string.h>
//数据
struct data
{
char name[50];
int num;
};
//设计节点
struct node
{
struct data data;
struct list_head list;
};
//头插入
void insert_node(struct list_head *head,struct data data)
{
//新建节点
struct node *xnew=malloc(sizeof(struct node));
xnew->data=data;
list_add(&xnew->list,head);
}
//尾插
void insert_node_tail(struct list_head *head,struct data data)
{
//新建节点
struct node *xnew=malloc(sizeof(struct node));
xnew->data=data;
list_add_tail(&xnew->list,head);
}
//遍历链表
void show_list(struct list_head *head)
{
struct node *pos=NULL;
list_for_each_entry(pos,head,list)
{
puts(pos->data.name);
}
}
//删除
void del_node(struct list_head *head,int num)
{
struct node *pos=NULL;
struct node *n=NULL;
list_for_each_entry_safe(pos,n,head,list)
{
if(pos->data.num == num)
{
list_del(&pos->list);
free(pos);
}
}
}
//查找
struct node *find_node(struct list_head *head,int num)
{
struct node *pos = NULL;
list_for_each_entry(pos,head,list)
{
if(pos->data.num == num)
{
puts("查找成功");
return pos;
}
}
return NULL;
}
//修改
void change_node(struct list_head *head,int org_data,int new_data)
{
struct node *pos = find_node(head,org_data);
if(pos!=NULL)
{
pos->data.num = new_data;
puts("修改成功");
}
}
int main()
{
//初始化头
struct list_head *head =malloc(sizeof(struct list_head));
INIT_LIST_HEAD(head);
//插入
struct data d;
strcpy(d.name,"hello");
d.num=1;
insert_node_tail(head,d);
strcpy(d.name,"goodmorning");
d.num=2;
insert_node_tail(head,d);
strcpy(d.name,"goodafternoon");
d.num=3;
insert_node_tail(head,d);
//修改
change_node(head,1,0);
//删除
del_node(head,0);
//遍历
show_list(head);
}
运行结果