idk why these stuffs get stashed for so long and I didn't ever commit them

This commit is contained in:
2025-11-06 09:43:54 +08:00
parent 5dbdfef1a1
commit e01c041259
232 changed files with 22806 additions and 1256 deletions

View File

@@ -0,0 +1,95 @@
#include<iostream>//cout,cin
using namespace std;
#include "SqStack.h"
char pause;
void dispmenu()
{ //显示主菜单
cout<<endl;
cout<<"1-初始化顺序栈\n";
cout<<"2-元素入栈\n";
cout<<"3-元素出栈\n";
cout<<"4-取栈顶元素\n";
cout<<"5-测栈空\n";
cout<<"6-显示栈元素\n";
cout<<"7-退出\n";
}
//主函数
int main()
{
int i;
int e;
SqStack<int> S;//建立容量为20、元素类型为整型的空顺序栈
system("cls"); // 清屏
int choice;
do
{
dispmenu(); // 显示主菜单
cout<<"Enter choice(1~7):";
cin>>choice;
switch(choice)
{
case 1: // 初始化顺序栈
cout<<"请输入要创建的顺序栈的长度";
cin>>i;
cout<<endl;
InitStack (S,i);
cout<<endl<<"创建成功!"<<endl;
break;
case 2: // 入栈
cout<<"输入要入栈的元素值:"<<endl;
cin>>e;
cout<<endl;
if(Push(S,e))
cout<<endl<<"入栈成功!"<<endl;
else
cout<<endl<<"入栈不成功!"<<endl;
break;
case 3: // 出栈
if(Pop(S,e))
{
cout<<endl<<"出栈元素为:"<<e<<endl;
cout<<endl<<"出栈成功!"<<endl;
}
else
cout<<endl<<"栈空,出栈失败!"<<endl;
break;
case 4: // 取栈顶元素
if(GetTop(S,e))
{
cout<<endl<<"栈顶元素为:"<<e<<endl;
}
else
cout<<endl<<"栈空!"<<endl;
break;
case 5: // 测栈空
if(StackEmpty(S))
cout<<endl<<"空栈!"<<endl;
else
cout<<endl<<"不是空栈!"<<endl;
break;
case 6: // 显示栈元素
DispStack(S);
cout<<endl;
cin.get(pause);
system("pause");
break;
case 7: // 退出
DestroyStack(S);
cout<<"结束运行"<<endl;
break;
default: // 无效选择
cout<<"Invalid choice\n";
break;
}
}while(choice!=7);
return 0;
}//end of main function

View File

@@ -0,0 +1,89 @@
template <class DT>
struct SqStack // 顺序栈
{
DT *base; // 栈首址
int top; // 栈顶指针
int stacksize; // 栈容量
};
//基本操作的实现
//【算法3.1】 // 初始化栈
template <class DT>
void InitStack(SqStack<DT> &S, int m)
{
S.base=new DT[m]; // 申请栈空间
if(S.base==NULL) // 申请失败,退出
{
cout<<"未创建成功!";
exit (1);
}
S.top=-1; // 设置空栈属性
S.stacksize=m;
}
//算法3.2】 // 销毁栈
template <class DT>
void DestroyStack(SqStack<DT> &S)
{
delete [] S.base; // 释放栈空间
S.top=-1;
S.stacksize=0; // 设置栈属性
}
//【算法3.3】 // 入栈
template<class DT>
bool Push(SqStack<DT> &S,DT e)
{
if(S.top==S.stacksize-1) // 栈满,不能入栈
return false; // 返回false
S.top++;
S.base[S.top]=e;
return true; // 入栈成功返回true
}
//【算法3.4】 // 出栈
template<class DT>
bool Pop(SqStack<DT> &S,DT &e)
{
if(S.top==-1) // 栈空
return false; // 返回false
e=S.base[S.top]; // 取栈顶元素
S.top--; // 栈顶指针下移
return true; // 出栈成功返回true
}
//【算法3.5】 // 获取栈顶元素
template<class DT>
bool GetTop(SqStack<DT> S,DT &e)
{
if(S.top==-1) // 栈空
return false; // 返回false
e=S.base[S.top]; // 栈非空,取栈顶元素
return true; // 返回true
}
// 测栈空
template<class DT>
bool StackEmpty(SqStack<DT> S)
{
if(S.top==-1) // 空栈返回true
return true;
else // 空栈返回false
return false;
}
//显示栈内容
template<class DT>
void DispStack(SqStack<DT> S)
{
int i=S.top;
while(i>=0)
{
cout<<S.base[i--]<<"\t";
}
cout<<endl;
}