#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main()
{
int i;
DATA x;
LIST head = NULL;
head = ListCreate();
if(NULL == head)
{
return 1;
}
for(i = 0;i < 6; i++)
{
x = i + 3;
// ListInsertHead(head,&x);
ListInsertTail(head,&x);
}
x = 5;
PtrNode p = ListFind(head,&x);
if(p == NULL)
{
printf("not find value!\n");
}
else
{
printf("data = %d\n",p->data);
}
ListDelete(head,&x);
ListDisplay(head);
ListDistroy(head);
return 0;
}
#ifndef _LIST_H__
#define _LIST_H__
struct node;
typedef int DATA;
typedef struct node * LIST;
typedef struct node * PtrNode;
typedef struct node * Position;
LIST ListCreate();
int ListIsEmpty(LIST);
int ListMakeEmpty(LIST);
int ListIsLast(LIST,Position);
int ListInsert(LIST,Position,const DATA *);
int ListInsertHead(LIST,const DATA *);
int ListInsertTail(LIST,const DATA *);
PtrNode ListFind(LIST,const DATA *);
PtrNode ListFindPrev(LIST,const DATA *);
int ListDelete(LIST,const DATA *);
void ListDisplay(LIST);
void ListDistroy(LIST);
struct node{
DATA data;
struct node * next;
};
#endif
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
LIST ListCreate()
{
PtrNode head = malloc(sizeof(*head));
if(head == NULL)
{
return NULL;
}
ListMakeEmpty(head);
return head;
}
int ListIsEmpty(LIST l)
{
return l->next == NULL;
}
int ListMakeEmpty(LIST l)
{
l->next = NULL;
}
int ListIsLast(LIST l,Position p)
{
return p->next == NULL;
}
int ListInsert(LIST l,Position prev,const DATA * data)
{
PtrNode cur = malloc(sizeof(*cur));
if(cur == NULL)
{
return 2;
}
cur->data = *data;
cur->next = prev->next;
prev->next = cur;
return 0;
}
int ListInsertHead(LIST l,const DATA * data)
{
return ListInsert(l,l,data);
}
int ListInsertTail(LIST l,const DATA * data)
{
Position tail = l;
for(;tail->next != NULL;tail = tail->next);
return ListInsert(l,tail,data);
}
PtrNode ListFind(LIST l, const DATA *data)
{
PtrNode p = l->next;
for(;p != NULL && p->data != *data;p = p->next);
return p;
}
PtrNode ListFindPrev(LIST l,const DATA *data)
{
PtrNode p = l;
for(;p->next != NULL && p->next->data!=*data;p=p->next);
return p;
}
int ListDelete(LIST l,const DATA *data)
{
Position prev = ListFindPrev(l,data);
if(!ListIsLast(l,prev))
{
Position q = prev->next;
prev->next = q->next;
free(q);
return 0;
}
return -1;
}
void ListDisplay(LIST l)
{
Position p = l->next;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
}
void ListDistroy(LIST l)
{
Position p = l->next;
Position q;
while(p != NULL)
{
q = p;
p = p->next;
free(q);
}
free(l);
}