#include<iostream> //顺序表(C++)
using namespace std;
#include <malloc.h>
#define LIST_INIT_SIZE 100 //初始分配空间
#define LISTINCREMENT 10 //分配增量
typedef int ElemType;
typedef int Status;
typedef struct {
ElemType* elem; //存储空间基址,指针,可指向变量,注:从elem[0]开始
int length; //当前长度
int listsize; //当前分配的存储容量
}Sqnode, * Sqlist;
Sqlist InitList_Sq() //构造一个空顺序表(用指针才能从根本上改变
{
Sqlist S;
S = (Sqlist)malloc(sizeof(Sqnode));
S->elem = (int*)malloc(LIST_INIT_SIZE * sizeof(int)); //分配100个int型内存空间
S->length = 0; //设置空表长度为0
S->listsize = LIST_INIT_SIZE; //设置初始的容量为100,即刚分配的空间
return S;
}
void PrintList_Sq(Sqlist S) { //输出表中元素
for (int i = 0; i < S->length; i++) {
cout << S->elem[i] << " ";
}
}
Status GetElem_Sq(Sqlist S, int i) //返回L中第i个元素的值
{
return S->elem[i - 1];
}
void Delete_Sq(Sqlist S, int i) { //删除第i个元素
S->length--;
for (int j = i - 1; j < S->length; j++) { //从第i+1个位置开始,整体向前移1位,覆盖第i个元素
S->elem[j] = S->elem[j + 1];
}
}
Status ListLength_Sq(Sqlist S) //返回L中元素个数
{
return S->length;
}
Status ListEmpty_Sq(Sqlist S) //判断是否为空表
{
if (S->length)
return false;
else
return true;
}
void ListInsert_Sq(Sqlist S, int i, int e) //在L中第i个位置插入新的元素e。位序!!
{
S->length++;
for (int j = S->length; j >= i; j--) { //从第i个位置开始,整体往后移1位,空出一个位置给e
S->elem[j] = S->elem[j - 1]; //最终把elem[i-1]向后移一位到elem[i],然后把e插入到elem[i-1]
}
S->elem[i - 1] = e;
}
int main()
{
Sqlist S;
int x, n;
S = InitList_Sq(); //创建空表
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> x;
ListInsert_Sq(S, i, x); //依次插入元素
}
int c = ListEmpty_Sq(S);
cout << c << endl;
PrintList_Sq(S);
return 0;
}
顺序表(C++)
于 2022-02-21 16:58:54 首次发布