>>步骤1:编写listnode.h文件
#ifndef __listnode_H__
#define __listnode_H__
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct NODE{
int data;
struct NODE*next;
}listnode;
listnode* list_create(void);
bool list_insert_head(listnode*H,int value);
bool list_delete(listnode*H,int value);
bool list_change(listnode*H,int pos,int value);
listnode*list_search(listnode*H,int value);
void list_show(listnode*H);
#endif
>>步骤2:编写listnode.c文件[增,删,改,查]
#include "listnode.h"
listnode* list_create()
{
listnode* H = NULL;
H = (listnode*)malloc(sizeof(listnode));
H->data = 0;
H->next = NULL;
return H;
}
bool list_insert_head(listnode*H,int value)
{
listnode* P = NULL;
P = (listnode*)malloc(sizeof(listnode));
P->data = value;
P->next = H->next;
H->next = P;
return true;
}
bool list_delete(listnode*H,int value)
{
listnode*P = H;
listnode*Q = NULL;
int i = 1;
while(P->next->data!=value)
{
P = P->next;
}
Q = P->next;
P->next = Q->next;
free(Q);
return true;
}
bool list_change(listnode*H,int pos,int value)
{
listnode*P = H;
int i = 1;
for(i;i<=pos;i++)
{
P=P->next;
}
P->data = value;
return true;
}
listnode* list_search(listnode*H,int value)
{
listnode*P = H;
while(P->data != value)
{
P=P->next;
}
return P;
}
void list_show(listnode*H)
{
listnode*P = H;
while((P->next)>0)
{
printf("%d\t",P->data);
P=P->next;
}
printf("%d\t",P->data);
}
>>步骤4:编写测试文件listnode_text.c
include "listnode.h"
int main(int argc, const char *argv[])
{
listnode* H;
listnode* P= NULL;
H=list_create();
printf("\n单链表:头插入\n");
list_insert_head(H,10);
list_insert_head(H,20);
list_insert_head(H,30);
list_insert_head(H,40);
list_insert_head(H,50);
list_show(H);
printf("\n单链表:查找20\n");
P = list_search(H,20);
printf("\n找到了data = %d\n",P->data);
printf("\n单链表:修改\n");
list_change(H,1,100);
list_change(H,2,200);
list_change(H,3,300);
list_change(H,4,400);
list_change(H,5,500);
list_show(H);
printf("\n单链表:删除\n");
list_delete(H,100);
list_delete(H,200);
list_delete(H,300);
list_delete(H,400);
list_delete(H,500);
list_show(H);
return 0;
}
>>步骤5:Makefile文件
VPATH=/home/yqj/单链表/
listnode_text:listnode.o listnode_text.c
gcc -g listnode.o listnode_text.c -o listnode_text
listnode.o:listnode.c listnode.h
gcc listnode.c -c -o listnode.o
.PHONY:clean
clean:
rm -rf listnode.o listnode_text
>>步骤6:验证结果
topeet@ubuntu:/home/yqj/desktop/单链表$ ./listnode_text
单链表:头插入
0 50 40 30 20 10
单链表:查找20
找到了data = 20
单链表:修改
0 100 200 300 400 500
单链表:删除
0