#ifndef SQLIST_H_INCLUDED
#define SQLIST_H_INCLUDED
#define MaxSize 50
#include <iostream>
using namespace std;
typedef int ElemType;
// 内核使用数组实现的顺序表
typedef struct SqList
{
ElemType data[MaxSize];
int length;
} SqList;
/**
包含头文件的写法
#include "D:\DataStructure\PublicLibrary\Sqlist\SqList.h"
初始化顺序表的驱动程序
SqList sqList;
ElemType array[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2,1};
initSqList(sqList, array, 10);
*/
// 使用数组初始化顺序表,size为初始化顺序表的长度
bool initSqList(SqList &sqList, ElemType array[], int length);
// 排序, flag为1表示升序,flag为0表示降序
bool sortSqList(SqList &sqList, int flag);
// 删除顺序表中指定的元素,并且在location中返回被删除元素原来的索引,假定顺序表中元素具有唯一性
bool deleteElement(SqList &sqList, ElemType delElem, int &location);
// 在顺序表中指定的第几个位置插入元素
bool insertElement(SqList &sqList, ElemType insertElem, int location);
// 判断顺序表是否为空
bool isEmpty(SqList sqList);
// 判断是否为满
bool isFull(SqList sqList);
// 遍历输出顺序表中的元素
void displaySqList(SqList sqList);
bool initSqList(SqList &sqList, ElemType array[], int length)
{
if(length > MaxSize)
{
cout << "初始化长度越界" << endl;
return false;
}
for(int i = 0; i < length; i++)
{
sqList.data[i] = array[i];
}
sqList.length = length;
return true;
}
bool sortSqList(SqList &sqList, int flag)
{
ElemType temp = 0;
if(flag == 1)
{
for(int i = 0; i < sqList.length - 1; i++)
{
for(int j = 0; j < sqList.length - i - 1; j++)
{
if(sqList.data[j] > sqList.data[j+1])
{
temp = sqList.data[j];
sqList.data[j] = sqList.data[j+1];
sqList.data[j+1] = temp;
}
}
}
}
else if(flag == 0)
{
for(int i = 0; i < sqList.length - 1; i++)
{
for(int j = 0; j < sqList.length - i - 1; j++)
{
if(sqList.data[j] < sqList.data[j+1])
{
temp = sqList.data[j];
sqList.data[j] = sqList.data[j+1];
sqList.data[j+1] = temp;
}
}
}
}
else
{
cout << "传参非法" << endl;
return false;
}
return true;
}
bool deleteElement(SqList &sqList, ElemType delElem, int &location)
{
location = -1;
if(isEmpty(sqList))
{
cout << "顺序表为空,删除失败" << endl;
return false;
}
for(int i = 0; i < sqList.length; i++)
{
if(sqList.data[i] == delElem)
{
location = i;
break;
}
}
if(location == -1)
{
cout << "需要删除的元素" << delElem <<"在顺序表中不存在" << endl;
return false;
}
for(int i = location; i < sqList.length-1; i++)
{
sqList.data[i] = sqList.data[i+1];
}
sqList.length--;
return true;
}
bool insertElement(SqList &sqList, ElemType insertElem, int location)
{
if(isFull(sqList))
{
cout << "顺序表已满,不允许再插入元素" << endl;
return false;
}
if(location < 0 || location > sqList.length+1)
{
cout << "插入位置非法" << endl;
return false;
}
for(int i = sqList.length - 1; i >= location-1; i--)
{
sqList.data[i+1] = sqList.data[i];
}
sqList.data[location-1] = insertElem;
sqList.length++;
return true;
}
void displaySqList(SqList sqList)
{
for(int i = 0; i < sqList.length; i++)
{
cout << sqList.data[i] << " ";
}
cout << endl;
}
bool isEmpty(SqList sqList)
{
if(sqList.length == 0)
return true;
return false;
}
bool isFull(SqList sqList)
{
if(sqList.length < MaxSize)
return false;
return true;
}
#endif // SQLIST_H_INCLUDED