//单键表
#include<iostream>
#include "List.h"
using namespace std;
struct Node
{
ElementType data;//数据部分
Position next;//指针部分
};
//int IsEmpty(List L)确定一个键表是否为空
int IsEmpty(List L) //这里的List为一个数据结构在头文件中定义的。
{
return L->next ==NULL;
}
//int IsLast(Position P,List L)测试当前位置是否是键表的末尾
int IsLast(Position P,List L)
{
return P->next==NULL;
}
//Position Find(ElementType X,List L)询找一个元素在键表中的位置
Position Find(ElementType X,List L)
{
Position head;
head=L;
while(head!=NULL&&head->data!=X)
head=head->next;
return head;
}
//Position FindPrevious(ElementType X,List L)
Position FindPrevious(ElementType X,List L)
{
Position P;
P=L;
while(P->next!=NULL&&P->next->data!=X)
P=P->next;
return P;
}
//void Delete(ElementType X,List L)删除键表中的元素X
void Delete(ElementType X,List L)
{
//下面这些是自己编写的,存在不完善的地方
// Position P;
// P=FindPrevious(X,L);//如果为最后一个元素则表示没有找到,这里并没有检查这种情况
// Position temp;
// temp=P->next->next;
// P->next=temp;//最后被删除的结点没有被释放
Position P,temp;
P=FindPrevious(X,L);
if(!IsLast(P,L))
{
temp=P->next;
P->next=temp->next;
free(temp);//用free释放
}
}
//void Insert(ElementType X,List L,Position P)用于在指定键表的指定位置插入指定元素,这里用的是在指定位置之后插入
void Insert(ElementType X,List L,Position P)
{
Position temp;
temp=(Position)malloc(sizeof(struct Node));
if(temp!=NULL)//这里要检查内存分配是否成功
{
temp->data = X;
temp->next=P->next;
P->next=temp;
}
else
cout<<"Error"<<endl;
}