1、静态顺序表的代码
#include<stdio.h>
#define Maxsize 10
typedef struct {
int data[Maxsize];
int length;
}SqList;
void InitList(SqList &L) {
for (int i = 0;i < Maxsize;i++) {
L.data[i] = 0;
}
L.length = 0;
}
void PrintList(SqList L) {
for (int i = 0;i < L.length;i++) {
printf("%d ", L.data[i]);
}
printf("\n%d ", L.length);
}
void SetList(SqList &L, int i, int e) {
L.data[i - 1] = e;
L.length++;
}
bool ListInsert(SqList &L, int i, int e) {
if(i<1|| i>L.length+1){
return false;
}
if (L.length >= Maxsize) {
return false;
}
for (int j = L.length;j >= i;j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
return true;
}
bool ListDelete(SqList &L, int i, int &e) {
if (i<1 || i>L.length) {
return false;
}
e = L.data[i - 1];
for (int j = i;j < L.length;j++) {
L.data[j - 1] = L.data[j];
}
L.length--;
return true;
}
int GetElem(SqList L,int i) {
return L.data[i - 1];
}
int main() {
SqList L;
InitList(L);
SetList(L, 1, 1);
SetList(L, 2, 2);
SetList(L, 3, 3);
SetList(L, 4, 4);
SetList(L, 5, 5);
SetList(L, 6, 6);
ListInsert(L, 3, 7);
int e = -1;
if (ListDelete(L, 3, e)) {
printf("已经删掉第3个元素,删掉的元素值为%d\n",e);
}
else {
printf("位序i不合法,删除失败!\n");
}
PrintList(L);
printf("次序为5的元素值为%d",GetElem(L,5));
return 0;
}
2、静态顺序表的运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200812111724827.png#pic_center)
3、动态顺序表的代码
#include<stdio.h>
#include<stdlib.h>
#define InitSize 10
typedef struct {
int *data;
int MaxSize;
int length;
}SeqList;
void InitList(SeqList &L) {
L.data = (int *)malloc(sizeof(int)*InitSize);
L.length = 0;
L.MaxSize = InitSize;
}
void IncreaseSize(SeqList &L, int len) {
int *p = L.data;
L.data = (int *)malloc(sizeof(int)*(L.MaxSize + len));
for (int i = 0;i < L.length;i++) {
L.data[i] = p[i];
}
L.MaxSize = L.MaxSize + len;
free(p);
}
void SetList(SeqList &L, int i, int e) {
L.data[i - 1] = e;
L.length++;
}
void PrintList(SeqList L) {
for (int i = 0;i < L.length;i++) {
printf("%d ", L.data[i]);
}
printf("\n%d ", L.length);
}
int LocateElem(SeqList L, int e) {
for (int i = 0;i < L.length;i++) {
if (L.data[i] == e)
return i + 1;
}
return 0;
}
int main() {
SeqList L;
InitList(L);
IncreaseSize(L, 5);
SetList(L, 1, 1);
SetList(L, 2, 2);
SetList(L, 3, 3);
SetList(L, 4, 4);
SetList(L, 5, 5);
SetList(L, 6, 6);
PrintList(L);
int e = 5;
printf("元素值等于%d的元素位序位于%d",e,LocateElem(L,e));
return 0;
}
4、动态顺序表的运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200812111847275.png#pic_center)