// list.h头文件
#ifndef _List_H
struct Node;typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
List MakeEmpty(List L);
int IsEmpty(List L);
int IsLast(Position p,List L);
Position Find(int x,List L);
void Delete(List L,int x);
void Insert(int x,List L,Position p);
void DeleteList(List L);
Position FindPrevious(int x,List L);
Position Header(List L);
Position First(List L);
Position Advance(Position P);
int Retrieve(Position P);
void printlist(List L);
#endif
#include "stdio.h"
#include "stdlib.h"
#include "list.h"
struct Node
{
int element;
Position next;
};
// 判断链表是否为空
int isEmpty(List L)
{
return L->next==NULL;
}
int IsLast(Position p,List L)
{
return p->next==NULL;
}
Position Find(int x,List L)
{
Position p=L->next;
while(p!=NULL&&p->element!=x)
p=p->next;
return p;
}
// 删除
void Delete(List L,int x)
{
Position p,TmpCell;
p=FindPrevious(x,L);
if(!IsLast(p,L))
{
TmpCell=p->next;
p->next=TmpCell->next;
}
}
// 查找前一项
Position FindPrevious(int x,List L)
{
Position p=L;
while(p->next!=NULL&&p->next->element!=x)
p=p->next;
return p;
}
// 插入
void Insert(int x,List L,Position p)
{
Position TmpCell;
TmpCell=(Position)malloc(sizeof(struct Node));
if(TmpCell==NULL)
{
printf("error");
return;
}
TmpCell->element=x;
TmpCell->next=p->next;
p->next=TmpCell;
}
// 删除链表
void DeleteList(List L)
{
Position p,Tmp;
p=L->next;
L->next=NULL;
while(p!=NULL)
{
Tmp=p->next;
free(p);
p=Tmp;
}
}
// 打印
void printlist(List L)
{
Position p=L->next;
while(p!=NULL)
{
printf("%d",p->element);
p=p->next;
}
}
main()
{
List L;
Position p;
L=(Position)malloc(sizeof(struct Node));
if(L==NULL)
{
printf("error");
return;
}
L->next=NULL;
p=(Position)malloc(sizeof(struct Node));
p->element=1;
p->next=L->next;
L->next=p;
Insert(2,L,p);
printlist(L);
}