用间接寻址的方法实现表

#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
//****************************
typedef int *addr;
typedef struct indlist *List;
typedef struct indlist
{
	int n;
	int maxsize;
	addr*table;//指向表中元素的指针数组;
}Indlist;

//****************************
addr NewNode()
{
	addr L;
	if((L=(addr)malloc(sizeof(int)))==0)  //为某节点分配内存,返回类型是 int *
	{
		cout<<"Exhausted memory"<<endl;
		exit(0);
	}
	return L;
}

//****************************
List ListInit(int size)			//初始化
{
	List L=(List)malloc(sizeof(Indlist));	//分配一个结构体的内存
	L->n=0;
	L->table=(addr*)malloc(sizeof(addr)*size);  //分配存储指针所需的内存
	return L;
	
}
//****************************
int ListEmpty(List L)  //判断表是否为空
{
	return L->n==0;
}
//****************************

int ListLength(List L)	//表的长度
{
	return L->n;
}
//****************************
int ListRetrieve(int k,List L)  //查找表中第K个位置的数
{
	if(k<1||k>L->n)
	{	
		cout<<"out of bounds"<<endl;
		exit(0);
	}
	return *L->table[k-1];
}
//****************************

int ListLocate(int x,List L)  //查找x在表中的位置
{
	int i;
	for(i=0;i<L->n;i++)
		if(*L->table[i]==x)
			return ++i;
	return 0;

}
//****************************
void ListInsert(int k,int x,List  L)   //插入新元素
{
	int i;
	if(k<0||k>L->n)
	{
		cout<<"out of bounds"<<endl;
			exit(0);
	}
	if(L->n==L->maxsize)
	{
		cout<<"out of bounds"<<endl;
		exit(0);
	}
	for(i=L->n-1;i>=k;i--)     //插入位置后面的指针往后移动一个位置
		L->table[i+1]=L->table[i];
	L->table[k]=NewNode();
	*L->table[k]=x;
	L->n++;
}

//****************************
int  ListDelete(int k,List L)   //同上,  往前移动一个位置
{
	int i,x;
	addr p;
	if(k<1||k>L->n)
	{
		cout<<"out of bounds"<<endl;
		exit(0);
	}
	p=L->table[k-1];
	x=*p;
	for(i=k;i<L->n;i++)
		L->table[i-1]=L->table[i];
	L->n--;
	free(p);
	return x;
}

//****************************
void PrintList(List L)    //打印表的内容
{
	int i;
	for(i=0;i<L->n;i++)
		cout<<*L->table[i]<<endl;
}
//****************************

int main()
{
	List L;
	int size,k,x;
	cout<<"请输入分配空间大小:"<<endl;
	cin>>size;
	L=ListInit(size);
	if(!ListEmpty(L))
	cout<<"empty!"<<endl;
	ListInsert(0,1,L);
	ListInsert(1,2,L);
	ListInsert(2,3,L);
	ListInsert(3,4,L);
	ListInsert(4,5,L);
	PrintList(L);
	cout<<"删除的k个位置的数:"<<endl;
	cin>>k;
	cout<<"删除的元素是:"<<ListDelete(k,L)<<endl;
	PrintList(L);
	cout<<"查找第k个位置的数:"<<endl;
	cin>>k;
	cout<<"第k个位置的数是:"<<ListRetrieve(k,L)<<endl;
	cout<<"查找x在表中的位置:"<<endl;
	cin>>x;
	cout<<"x在表中的位置是:"<<ListLocate(x,L)<<endl;

	return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值