数据结构之顺序表的基本运算
2016-04-02 12:32
791 查看
#include <iostream> #include <malloc.h> #include <cstdio> #include <cstring> using namespace std; #define MaxSize 100 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int length; } SqList; void InitList(SqList *&L) //初始化顺序表L { L=(SqList *)malloc(sizeof (SqList)); L->length=0; } void ListInsert(SqList *&L,ElemType a[],int n) //采用尾插法依次插入元素a,b,c,d,e { for(int i=0; i<n; i++) L->data[i]=a[i]; L->length=n; } void DispList(SqList *L) //输出顺序表L { for(int i=0; i<L->length; i++) cout<<L->data[i]<<" "; cout<<endl; } int ListLength(SqList *L) //输出顺序表L的长度 { return(L->length); } bool ListEmpty(SqList *L) //判断顺序表L是否为空 { return(L->length==0); } void GetElem(SqList *L,int j) //输出顺序表的第i个元素 { for(int i=0; i<L->length; i++) { if(i==(j-1)) cout<<L->data[i]<<endl; } } void Displocation(SqList *L,ElemType a) //输出元素a的位置 { for(int i=0; i<L->length; i++) { if(L->data[i]==a) //找出a的位置 cout<<i+1<<" "; } cout<<endl; } bool ListInsert(SqList *&L,int i,ElemType e) //插入数据元素 { int j; if(i<1||i>L->length+1) //逻辑序号化成物理序号 return false; i--; for(j=L->length; j>i; j--) L->data[j]=L->data[j-1]; L->data[i]=e; L->length++; //对的话长度+1 return true; } bool ListDelete(SqList *&L,int i) //删除数据元素 { int j; if(i<1||i>L->length+1) return false; i--; for(j=i; j<L->length; j++) L->data[j]=L->data[j+1]; L->length--; //删除一个元素后长度-1 return true; } void DestoryList(SqList *&L) //销毁顺序表 { free(L); } int main() { char a[10]; char b='a'; cout<<"顺序表的基本运算如下:"<<endl; SqList *L; InitList(L); cout<<"已初始化顺序表"<<endl; cout<<"采用尾插法依次插入元素 "; gets(a); ListInsert(L,a,strlen(a)); cout<<"输出顺序表:"; DispList(L); cout<<"顺序表的长度:"<<ListLength(L)<<endl; cout<<"顺序表是否为空:"; if(ListEmpty(L)) cout<<"是"<<endl; else cout<<"否"<<endl; cout<<"顺序表L的第三个元素为:"; GetElem(L,3); cout<<"输出元素"<<b<<"的位置:"; Displocation(L,b); ListInsert(L,4,'f'); cout<<"已在第4个元素位置上插入元素f"<<endl; cout<<"输出顺序表:"; DispList(L); ListDelete(L,3); cout<<"已删除第3个位置上的元素"<<endl; cout<<"输出顺序表:"; DispList(L); DestoryList(L); cout<<"顺序表已释放!"<<endl; return 0; }
运行结果:
相关文章推荐
- 数据结构3
- 循环队列中判断队满与队空
- 二叉树和二叉查找树
- 队列的实现
- 单链表集合求交集
- POJ 1061-青蛙的约会(拓展欧几里得)
- 【Redis基本数据结构】动态字符串
- 【Redis基本数据结构】链表
- 重学数据结构系列之——森林之并查集(Disjoint set)
- 数据结构之单链表(C++实现)
- 面试/笔试数据结构之排序算法篇
- 数据结构实验之排序二:交换排序
- 数据结构实验之排序一:一趟快排
- 1474 数据结构:进制转换
- 1467 数据结构:一元多项式加法
- 1465 数据结构:有序链表的合并
- 1464 数据结构:线性表插入元素
- 1462 数据结构:线性表的插入
- 链队列的基本操作
- 【Python】Python的数据分析(三)——数据文件及数据结构