单链表的实现主要包括链表的添加、遍历、查找、删除操作。具体过程还有待改进。
list.h
#ifndef __LIST_H__
#define __LIST_H__
#include <stdlib.h>
#include <stdio.h>
typedef struct _list
{
int data;
struct _list *next;
}list;
list *list_append(list **head,int data);
list *list_search(list *head,int data);
int list_delete(list *head,list *del);
void list_print(list *head);
void list_destroy(list **head);
#endif
list.c
#include "list.h"
list *list_append(list **head,int data)
{
list *last,*phead;
phead=*head;
if((last=(list *)malloc(sizeof(list)))==NULL)
return NULL;
last->data=data;
last->next=NULL;
if(phead==NULL)
{
*head=last;
return last;
}
while(phead!=NULL)
{
if(phead->next==NULL)
{
phead->next=last;
return last;
}
phead=phead->next;
}
return NULL;
}
list *list_search(list *tmp,int data)
{
while(tmp!=NULL)
{
if(tmp->data==data)
return tmp;
tmp=tmp->next;
}
return NULL;
}
int list_delete(list *head,list *del)
{
while(head!=NULL)
{
if(head->next==del)
{
head->next=del->next;
return 0;
}
head=head->next;
}
return -1;
}
void list_print(list *head)
{
printf("Your input is:\n");
while(head!=NULL)
{
printf("%2d\t",head->data);
head=head->next;
}
printf("\n");
}
void list_destroy(list **head)
{
list *phead=*head,*tmp;
while(phead!=NULL)
{
tmp=phead;
phead=phead->next;
free(tmp);
}
*head=NULL;
}
下面这个是一个简单的测试
main.c
#include <stdio.h>
#include "list.h"
int main()
{
list *head=NULL,*tmp;
int data;
while(1)
{
printf("Input the datas you want to store in the list(end with any chactor but number):\n");
while(scanf("%d",&data))
list_append(&head,data);
setbuf(stdin,NULL);
list_print(head);
//search a data
printf("Print a data to search:");
scanf("%d",&data);
setbuf(stdin,NULL);
tmp=list_search(head,data);
if(tmp==NULL)
{
printf("Do not found the value\n");
}
else
{
char ans;
printf("Found %d\nDo you want to delete id?y/n:",tmp->data);
setbuf(stdin,NULL);
scanf("%c",&ans);
if(ans=='y')
{
list_delete(head,tmp);
list_print(head);
}
}
//delete all the data
list_destroy(&head);
}
}