目录
一、顺序表的定义
二、顺序表的分配
静态分配
动态分配
三、动态扩展
四、顺序表完整代码如下
顺序表具有的功能:
文章来源地址https://uudwc.com/A/LapzV
一、顺序表的定义
线性表的顺序存储又称顺序表。它是一组地址连续的存储单元存储线性表中的数据元素,从而使得逻辑上相邻的两个元素在物理位置上也相邻。
二、顺序表的分配
顺序表可以用静态分配,也可以用动态分配。
静态分配
分配一定的存储空间,大小和空间都已经固定,不能改变。
#define InitSize 100 //初始表长
typedef struct{
ElemType *elem; //顺序表元素类型
int MaxSize;
int length;
}SqList;
动态分配
在分配一定的存储空间后,大小和空间可以改变。
C的初始动态分配语句为:
L.elem=(ElemType *)malloc(InitSize*sizeof(ElemType));
C++的初始动态分配语句为:
L.elem=new ElemType[InitSize];
三、动态扩展
静态分配是存储空间装满后,就不能再添加元素,若再加入元素,就会导致内存溢出。
动态扩展是存储空间可以扩充,但需要移动大量的元素,导致操作效率降低,而且需要一片更大的连续存储空间,如果没有这样的空间,就会导致分配失败。
void IncreaseSize(SqList &L,int len){
ElemType *p=L.elem;
L.elem=(ElemType *)malloc((L.MaxSize+len)*sizeof(ElemType));
for(int i=0;i<L.length;i++){
L.elem[i]=p[i];
}
L.MaxSize=L.MaxSize+len;
free(p);
}
四、顺序表完整代码如下
顺序表具有的功能:
(1)初始化线性表
(2)插入元素
(3)按位查找
(4)按值查找
(5)删除元素
(6)打印输出线性表
#include<stdio.h>
#include<stdlib.h>
#define InitSize 10
typedef int ElemType;//整型
typedef struct{
ElemType *elem; //顺序表元素类型
int MaxSize;
int length;
}SqList;
void InitList(SqList &L){//初始化
L.elem=(ElemType *)malloc(InitSize*sizeof(ElemType));
L.length=0;
L.MaxSize=InitSize;
}
void IncreaseSize(SqList &L,int len){
ElemType *p=L.elem;
L.elem=(ElemType *)malloc((L.MaxSize+len)*sizeof(ElemType));
for(int i=0;i<L.length;i++){
L.elem[i]=p[i];
}
L.MaxSize=L.MaxSize+len;
free(p);
}
bool ListInsert(SqList &L,int i,ElemType e){//插入
if(i<1||i>L.length+1){
printf("插入失败\n");
return false;
}
if(L.length>=L.MaxSize){
printf("插入失败\n");
return false;
}
for(int j=L.length;j>=i;j--){
L.elem[j]=L.elem[j-1];
}
L.elem[i-1]=e;
L.length++;
printf("插入成功\n");
return true;
}
bool ListDelete(SqList &L,int i,ElemType &e){//删除
if(i<1||i>L.length)
{printf("删除失败\n");
return false;}
e=L.elem[i-1];
for(int j=i;j<L.length;j++){
L.elem[j-1]=L.elem[j];
}
L.length--;
printf("删除成功\n");
return true;
}
int GetElem(SqList L,int i){//按位查找
return L.elem[i-1];
}
int LocateElem(SqList L,ElemType e){//按值查找
for(int i=0;i<L.length;i++){
if(L.elem[i]==e)
return i+1;
}
return 0;
}
void PrintList(SqList L){ //打印顺序表
for(int i=0;i<L.length;i++)
printf("%d ",L.elem[i]);
printf("\n");
}
int main(){
SqList L;
InitList(L);//初始化线性表
//int e=-1; //初始化插入值
ListInsert(L,1,1); //在第1个位置插入1
ListInsert(L,2,2);
ListInsert(L,3,3);
ListInsert(L,3,2); //在第3个位置插入2
PrintList(L); //打印顺序表
return 0;
}
文章来源:https://uudwc.com/A/LapzV