循环后面加"{ }"是个好行为,不然很容易犯低级错误
导致一个变量的位置放错了,看了很久没看出Bug;
//顺序表
#include<iostream>
#include<windows.h>
using namespace std;
const int MAXSIZE = 25;
typedef struct {
int elem[MAXSIZE];//内存空间大小
int Last;//表长
}SeqList;
int main()
{
int Length;
int Option = 0;
SeqList L;
L.Last = 0;
cout <<"请输入线性表长度: ";
cin >> Length;
system("CLS");
cout <<endl<< "-----------1. 创建顺序表."<<endl;
cout << " -----------2. 输出顺序表元素." << endl;
cout << " -----------3. 顺序表元素排序. " << endl;
cout << " -----------4. 向顺序表中插入元素." << endl;
cout << " -----------5. 删除顺序表单个元素. " << endl;
cout <<endl<< "请输入你的选择: ";
cin >> Option;
void CreateList(SeqList* L, int Length);
void PrintList(SeqList* L, int Length);
void SequenceList(SeqList* L, int Length);
void DeleteList(SeqList* L, int Length);
void InsertList(SeqList*L, int Length);
switch(Option)
{
case 1: CreateList(&L, Length); break;
case 2: PrintList(&L, Length); break;
case 3: SequenceList(&L, Length); break;
case 4: InsertList(&L, Length); break;
case 5: DeleteList(&L, Length); break;
default: cout << "输入错误!"; break;
}
cout << endl;
return 0;
}
//创建顺序表
void CreateList(SeqList* L, int Length)
{
int i;
cout << "请输入顺序表元素:";
for (i = 0; i < Length; i++)
{
cin>>L->elem[i];
L->Last = Length;
if (Length >= MAXSIZE)
{
cout << endl << "表满!" << endl;
}
}
for (i = 0; i < Length; i++)
{
cout << L->elem[i] << " ";
}
}
//输出表
void PrintList(SeqList* L, int Length)
{
int i;
for (i = 0; i < L->Last; i++)
{
cout << L->elem[i] << ", ";
}
cout << endl;
}
//对数据元素排序
void SequenceList(SeqList* L, int Length)
{
int Temp = 0;
for (int i = 0; i <Length-1; i++)
{
for (int j = 0; j <Length-1-i; j++)
{
if (L->elem[j] > L->elem[j + 1])
{
Temp = L->elem[j];
(L->elem[j]) = (L->elem[j + 1]);
L->elem[j + 1] = Temp;
}
}
}
cout << endl;
}
//删除表的某个元素
void DeleteList(SeqList* L, int Length)
{
int DeData = 0;
cout << "要删除第几个元素:";
cin>>DeData;
for (int i = DeData; i < L->Last; i++)
{
L->elem[i - 1] = L->elem[i];
}
L->Last --;
for (int k = 0; k < L->Last; k++)
{
cout << L->elem[k] << " ";
}
cout << endl;
}
//往表中插入元素
void InsertList(SeqList* L, int Length)
{
int InsertData = 0;
int i = 0;
int InDataLocation = 0;
cout << "请输入要插入的元素: ";
cin >> InsertData;
cout << endl;
cout << "请输入要插入的位置: ";
cin >> InDataLocation;
cout << endl;
if (InDataLocation > L->Last+1)
{
cout << "插入位置超过表的最大长度,请重新输入!"<< endl<<endl;
InsertList( L, Length);
}
else
{
for (int i = L->Last; i >= InDataLocation - 1; i--)
{
L->elem[i + 1] = L->elem[i];
}
L->elem[InDataLocation - 1] = InsertData;
L->Last++;
cout << "插入后的表为:";
PrintList(L, Length);
}
cout << endl;
}