源代码:list.h
#ifndef _LIST_H
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
struct node{
int val;
struct node * next;
};
typedef struct node* Hlist;
typedef struct node* Position;
void insert(Position pos,int num);
void deletenode(int num,Hlist head);
Position getPrevious(int num,Hlist head);
Position find(int num,Hlist head);
void printlist(Hlist head);
#endif
list.c
#include"list.h"
void insert(Position pos,int num)
{
Position temp=malloc(sizeof(struct node));
if (temp==NULL)
printf("allocate memory failed!");
temp->val=num;
temp->next=pos->next;
pos->next=temp;
}
void deletenode(int num,Hlist head)
{
Position pos=getPrevious(num,head);
if(pos==NULL)
printf("fail to delete num of node");
Position temp=pos->next;
pos->next=pos->next->next;
free(temp);
}
Position getPrevious(int num,Hlist head)
{
Position p=head->next;
while(p->next!=NULL){
if(p->next->val==num)
return p;
p=p->next;
}
return NULL;
}
Position find(int num,Hlist head)
{
Position p=head->next;
while(p!=NULL)
{
if(p->val==num)
return p;
p=p->next;
}
return NULL;
}
void printlist(Hlist head)
{
Position p= head->next;
while(p!=NULL)
{
printf("add:%d value:%d\n",p,p->val);
p=p->next;
}
}
int main()
{
Hlist head=malloc(sizeof(struct node));
head->val=0;
head->next=NULL;
insert(head,6);
insert(head,7);
insert(head,8);
insert(head,9);
deletenode(7,head);
printlist(head);
printf("-------------------\n");
printf("the %d value of add: %d\n",8,find(8,head));
free(head);
return 0;
}
运行结果:
add:166887496 value:9
add:166887480 value:8
add:166887448 value:6
-------------------
the 8 value of add: 166887480
这主要实现链表插入,删除,查找,显示。希望对读者有学习上的帮助。