**
数据结构与算法(C++版) 线性表顺序存储结构简单代码:
**
#include “pch.h”
#include
using namespace std;
#define LISTSIZE 100 //数组的最大长度
typedef int DataType; //让int另名为DataType
typedef struct SeqList { //让SeqList{…}整个结构体另名为SeqList,因此以后用到 SeqList则直接会隐含有该结构体
DataType data[LISTSIZE];
int nLength;
}SeqList;
void initList(SeqList*list) { //初始化线性表的长度
list->nLength = 0;
}
bool listEmpty(SeqList*list) { //判断线性表是否为空
return list->nLength == 0;
}
DataType getNode(SeqList*list,int i) { //返回该数值
if (i<0 || i>list->nLength - 1)
return 0;
return list->data[i];
}
DataType insert(SeqList*list, int i, DataType x) {
int insertPosition = i; //在某位置插入某个值
if (list->nLength == LISTSIZE)
return -1;
if (i < 0)
insertPosition = 0; //当i<0时在表头插入该值
if (i > list->nLength - 1)
insertPosition = list->nLength;
for (int j = list->nLength - 1; j >= insertPosition; j–) {
list->data[j + 1] = list->data[j];
}
list->data[insertPosition] = x;
list->nLength++;
return list->data[insertPosition];
}
DataType deleteList(SeqList*list,int i){ //删除某个元素。
if (i < 0 || i >= list->nLength)
return -1;
for (int j = i; j < list->nLength - 1; j++)
list->data[j] = list->data[j + 1];
list->nLength–;
return list->nLength;
}
DataType getUnion(SeqLista,SeqListb){ //将a,b的元素结合,并b的元素在原a的元素后面
if (a->nLength + b->nLength > LISTSIZE)
return -1;
for (int i = 0; i < b->nLength; i++) {
DataType e = b->data[i];
insert(a, a->nLength, e);
}
return a->nLength;
}
int main() {
SeqList sl,a,b;
initList(&sl);
bool empty = listEmpty(&sl);
cout << empty << endl;
sl.data[0] = 2;
sl.nLength++;
sl.data[1] = 9;
sl.nLength++;
DataType pNode = getNode(&sl, 1);
cout << pNode << endl;
DataType it=insert(&sl, -1, 10);
cout << it << endl;
cout << sl.data[1] << endl;
cout << endl;
cout << sl.nLength << endl;
cout << deleteList(&sl, 1) << endl;
cout << sl.data[1] << endl;
a.data[0] = 10;
a.data[1] = 8;
a.data[2] = 7;
a.nLength = 3;
b.data[0] = 6;
b.data[1] = 7;
b.nLength = 2;
cout << getUnion(&a, &b) << endl;
return 0;
}