顺序表示的栈——顺序栈2——出入栈操作
出栈和入栈 利用顺序栈的基本操作,将元素A,B,C,D,E,F,G,H依次入栈,再将栈顶元素即H,G出栈。然后把X,Y入栈,最后将元素全部出栈,并依次输出出栈元素。 SeqStack.h#pragma once#include <iostream>using namespace std;#define StackSize 100typedef char...
·
出栈和入栈
利用顺序栈的基本操作,将元素A,B,C,D,E,F,G,H依次入栈,再将栈顶元素即H,G出栈。然后把X,Y入栈,最后将元素全部出栈,并依次输出出栈元素。
SeqStack.h
#pragma once
#include <iostream>
using namespace std;
#define StackSize 100
typedef char DataType;
typedef struct
{
DataType stack[StackSize];
int top;
}SeqStack;
void InitStack(SeqStack *S)
/*初始化栈*/
{
S->top = 0;
}
int StackEmpty(SeqStack S)
/*判断是否为空*/
{
if (S.top==0)
{
return 1;
}
else
{
return 0;
}
}
int GetTop(SeqStack S,DataType *e)
/*取栈顶元素*/
{
if (S.top<=0)
{
cout << "栈已经空了!" << endl;
return 0;
}
else
{
*e = S.stack[S.top - 1];
return 1;
}
}
int PushStack(SeqStack *S,DataType e)
/*将元素e入栈*/
{
if (S->top>=StackSize)
{
cout << "栈已经满,不能讲元素入栈!" << endl;
return 0;
}
else
{
S->stack[S->top] = e;
S->top++;
return 1;
}
}
int PopStack(SeqStack *S, DataType *e)
/*将栈顶元素出栈,赋值给e*/
{
if (S->top==0)
{
cout << "栈中已经没有元素,不能进行出栈操作!" << endl;
return 0;
}
else
{
S->top--;
*e = S->stack[S->top];
return 1;
}
}
int StackLength(SeqStack S)
/*求栈的长度*/
{
return S.top;
}
void ClearStack(SeqStack *S)
/*清空栈*/
{
S->top = 0;
}
main.cpp
#include <stdlib.h>
#include "SeqStack.h"
#include <iomanip>
void main()
{
SeqStack S;
int i;
DataType a[] = { 'A','B','C','D','E','F','G','H' };
DataType e;
InitStack(&S);
for (i = 0; i < sizeof(a) / sizeof(a[0]);i++)
{
if (PushStack(&S,a[i])==0)
{
cout << "栈已满,不能进栈!";
return;
}
}
cout << "依次出栈的元素是:";
if (PopStack(&S,&e)==1)
{
cout <<setw(4)<< e;
}
if (PopStack(&S,&e)==1)
{
cout <<setw(4)<< e;
}
cout << endl;
cout << "当前的栈顶元素是:";
if (GetTop(S,&e)==0)
{
cout << "栈已空!";
return;
}
else
{
cout << setw(4)<<e << endl;
}
cout << "将元素X,Y依次入栈。" << endl;
if (PushStack(&S,'X')==0)
{
cout << "栈已满,不能入栈!";
return;
}
if (PushStack(&S,'Y')==0)
{
cout << "栈已满,不能入栈!";
return;
}
cout << "当前栈中元素个数是:" <<setw(4)<< StackLength(S) << endl;
cout << "将栈中元素依次出栈,出栈的序列是:" << endl;
while (!StackEmpty(S))
{
PopStack(&S, &e);
cout <<setw(4)<< e << " ";
}
cout << endl;
system("pause");
}
结果:

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)