用间接寻址的方法实现表
#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; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: Intel RealSense开发一
- 下一篇: Fishhook替换C函数的原理