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,92 @@
#include<iostream> //cout,cin
using namespace std;
#include "LinkStack.h"
void dispmenu()
{//显示主菜单
cout<<endl;
cout<<"1-初始化链栈\n";
cout<<"2-元素入栈\n";
cout<<"3-元素出栈\n";
cout<<"4-取栈顶元素\n";
cout<<"5-测栈空\n";
cout<<"6-显示栈元素\n";
cout<<"0-退出\n";
}
char pause;
//主函数
int main()
{
int e;
LNode<int> * S;
system("cls"); // 清屏
int choice;
do
{
dispmenu(); //显示主菜单
cout<<"Enter choice(1~60 退出):";
cin>>choice;
switch(choice)
{
case 1: //初始化链栈
InitStack(S);
cout<<endl<<"创建成功!"<<endl;
break;
case 2: //入栈
cout<<"输入要入栈的元素值:"<<endl;
cin>>e;
cout<<endl;
if(Push(S,e))
{
cout<<endl<<"入栈成功!栈中元素为:"<<endl;
DispStack(S);
}
else
cout<<endl<<"入栈不成功!"<<endl;
break;
case 3: //出栈
if(Pop(S,e))
{
cout<<endl<<"出栈成功!出栈元素为:"<<e<<endl;
cout<<"出栈后,栈中元素为"<<endl;
DispStack(S);
}
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 0: //退出
DestroyStack(S);
cout<<"结束运行Bye-bye"<<endl;
break;
default: //非法选择
cout<<"Invalid choice\n";
break;
}
}while(choice!=0);
return 0;
}//end of main function

View File

@@ -0,0 +1,94 @@
template <class DT>
struct LNode //结点
{
DT data; //数据域,存储数据元素值
LNode *next;//指针域,指向下一个结点
};
//【算法3.6】
template <class DT>
void InitStack(LNode<DT> *&S)//创建空链栈
{
//L=new LNode<DT>; //创建头结点
//if(!L) exit(1); //创建失败,结束运行
S=NULL;
}
//【算法3.7】
template <class DT>
void DestroyStack(LNode<DT> *(&S))//释放链栈
{
LNode<DT> *p;
while(S)//从头结点开始,依次释放结点
{
p=S;
S=S->next;
delete p;
}
//L=NULL;//头结点指向空
}
//【算法3.8】
template<class DT>
bool Push(LNode<DT> *&S,DT e)
{
LNode<DT> *p;
p=new LNode<DT>;
if(!p) return false; //创建失败,结束运行
p->data=e; // 新结点赋值
p->next=S; //结点S链接到p结点之后
S=p;
return true; // 插入成功返回true
}
//【算法3.9】
template<class DT>
bool Pop(LNode<DT> *&S,DT &e)
{
LNode<DT> *p;
if(S==NULL) return false;
p=S;
e=p->data;
S=S->next;
delete p;
return true; // 删除成功返回true
}
//【算法3.10】
template<class DT>
bool GetTop(LNode<DT> *S,DT &e)
{
LNode<DT> *p;
if(S==NULL) return false;
p=S;
e=p->data;
return true; // 删除成功返回true
}
//测栈空
template<class DT>
bool StackEmpty(LNode<DT> *S)
{
if(S==NULL)
return true;
else
return false;
}
//显示栈内容
template<class DT>
void DispStack(LNode<DT> *S)
{
LNode<DT> *p;
p=S;
while(p)
{
cout<<p->data<<"\t";
p=p->next;
}
cout<<endl;
}