单向链表
1、设计节点
2、初始化空链表
3、新建一个节点
4、插入节点
5、删除节点
6、移动节点
7、查找节点
8、遍历链表
代码:
#include
#include
#include
#include
#include
struct student
{
char *name;
int age;
float score;
};
typedef struct node
{
struct student stu;
struct node *next;
}NODE,*PNODE; //struct node = NODE struct node * = PNODE
PNODE init_singly_list(void)
{
PNODE phead = (PNODE)malloc(sizeof(NODE));
//判断是否成功
if(phead == NULL)
{
printf("init_singly_list falues");
exit(-1);
}
//防止野指针
phead->next =NULL;
return phead;
}
PNODE make_node(char *name,int age,float score)
{
PNODE pnew = malloc(sizeof(NODE));
if(pnew == NULL)
{
printf(“make_node fail\n”);
//return NULL;
}
else
{
pnew->stu.name = malloc(20*sizeof(char));
if(pnew->stu.name == NULL)
{
printf("malloc name space fail\n");
free(pnew);
pnew = NULL;
}
else
{
pnew->stu.age = age;
pnew->stu.score = score;
strcpy(pnew->stu.name,name);
printf("test\n");
pnew->next = NULL;
}
}
printf("创建成功!\n");
return pnew;
}
bool insert_node_tail(PNODE p,PNODE new)
{
while(p->next != NULL)
{
p=p->next;
}
new->next = p->next;
p->next = new;
printf("插入尾成功!\n");
return true;
}
bool insert_node_head(PNODE p,PNODE new)
{
while(p->next != NULL)
{
p=p->next;
}
new->next = p->next;
p->next = new;
printf("插入头成功!\n");
return true;
}
bool delete_single_list_node(PNODE p,PNODE delete)
{
if(p == NULL|| delete == NULL)
{
return false;
}
while(p->next!=delete && p->next != NULL)
{
p=p->next;
}
p->next = delete->next;
delete->next = NULL;
printf(“delete succes!\n”);
return true;
}
PNODE find_node(PNODE p,char *name)
{
PNODE t = p->next;
while(t != NULL)
{
printf("test\n");
if(strcpy(t->stu.name,name)!=0)
{
printf("find succes!\n");
return t;
}
t=t->next;
}
return NULL;
}
void show_single_list(PNODE p)
{
while(p->next != NULL)
{
p=p->next;
printf("%s %d %f ",p->stu.name,p->stu.age,p->stu.score);
}
printf("\n");
}
void move_node(PNODE delete_prev,PNODE delete,PNODE pos)
{
if(delete_prev == NULL ||delete == NULL ||pos == NULL)
{
return
}
delete_single_list_node(delete_prev,delete);
insert_node(delete_prev,delete);
insert_node_tail(pos,delete);
printf(“插入成功!\n”);
}
int main(void)
{
PNODE student=init_singly_list();
PNODE find;
PNODE pnew,pnew1;
pnew=make_node("jwj",2,3);
pnew1=make_node("cjs",5,6);
insert_node_head(student,pnew);
insert_node_head(student,pnew1);
show_single_list(student);
find=find_node(student,"jwj");
printf("%s %d %f \n",find->stu.name,find->stu.age,find->stu.score);
delete_single_list_node(student,find);
show_single_list(student);
return 0;
}