单键表操作

//单键表

#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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值