顺序表的结构定义
存于SeqList.h中
#ifndef __SEQLIST_H__
#define __SEQLIST_H__
#include <bits/stdc++.h>
using namespace std;
#define initSize 30
typedef int DataType;
typedef struct
{
DataType *data;
int maxSize, n; //当前最大长度 和 元素个数
} SeqList;
#endif
顺序表的基本操作
存于SeqList.cpp中
#include "SeqList.h"
using namespace std;
void initList(SeqList& L){
L.data = (DataType *)malloc(initSize*sizeof(DataType));
if(!L.data){cout << "分配错误\n"; exit(1);}
L.maxSize = initSize;
L.n = 0;
}
void clearList(SeqList& L){ //清空顺序表
L.n = 0;
}
int Length(SeqList& L){ //计算顺序表长度
return L.n;
}
bool isEmpty(SeqList& L){
return L.n == 0;
}
bool isFull(SeqList& L){
return L.n == L.maxSize;
}
bool creatList(SeqList& L, DataType A[], int n){ //从数组A 创建顺序表;储存失败返回false
L.data = (DataType *)malloc(initSize*sizeof(DataType));
if(!L.data) return false;
for(int i = 0; i < n; i ++) L.data[i] = A[i];
L.maxSize = initSize; L.n = n;
return true;
}
int Search(SeqList& L, DataType x){
for(int i = 0; i < L.n; i ++)
if(L.data[i] == x) return i;
return -1;
}
int Locate(SeqList& L, int i){
//函数返回第i个元素的物理位置
if(i >= 0 && i < L.n) return i - 1;
else return -2;
}
bool Insert(SeqList& L, int i, DataType x){
//将新元素x插入到表中的第i个位置
if(L.n == L.maxSize) return false;
if(i < 0 || i > L.n + 1) return false;
for(int j = L.n - 1; j >= i - 1; j --){
L.data[j + 1] = L.data[j];
}
L.data[i - 1] = x; L.n ++;
return true;
}
bool Remove(SeqList& L, int i, DataType& x){
//删除顺序表中第i个元素,并把删除值返回给x
if(i < 0 || i >= L.n) return false;
x = L.data[i - 1];
for(int j = i - 1; j < L.n; j ++){
L.data[j] = L.data[j + 1];
}
L.n --;
return true;
}
void printList(SeqList& L){
for (int i = 0; i < L.n; i++)
{
cout << L.data[i] << ", ";
}
}
顺序表的操作示例
#include "SeqList.cpp"
using namespace std;
void Merge(SeqList& LA, SeqList& LB){
// 集合的合并运算,结果存于LA
int n = Length(LA), m = Length(LB);
for (int i = 0; i < m; i++)
{
DataType x = LB.data[i];
if(Search(LA, x) == -1){
Insert(LA, n + 1 , x);
n ++;
}
}
}
void Intersection(SeqList& LA, SeqList& LB){
//取LA和LB交集结果存于LA中
int n = Length(LB);
for(int i = 0; i < n; i ++){
DataType x = LB.data[i];
int k = Search(LA, x);
if(k != -1) Remove(LA, k, x);
}
}
int main(){
SeqList LA, LB;
int A[5] = {0, 1, 2, 3, 4};
int B[5] = {3, 4, 5, 6, 7};
creatList(LA, A, 5);
creatList(LB, B, 5);
Merge(LA, LB);
printList(LA);
system("pause");
return 0;
}