考研复习之栈(一)

最简单的顺序栈:

#pragma once
#define StackSize 100
typedef char Datatype;
class StackTest
{
public:
    StackTest();
    ~StackTest();
};
typedef struct {
    Datatype stack[StackSize];
    int top;
}Stack;
void InitStack(Stack *S);
int StackLength(Stack S);
int getTopOfStack(Stack *S, Datatype *e);
int PushStack(Stack *S, Datatype e);
int PopStack(Stack *S, Datatype *e);
void ClearStack(Stack *S);

完整代码:

#include "StackTest.h"
#include<iostream>
using namespace std;


StackTest::StackTest()
{
}


StackTest::~StackTest()
{
}

void InitStack(Stack *S)
{
    S->top = 0;
}

int StackLength(Stack S)
{
    return S.top;
}

int getTopOfStack(Stack * S, Datatype * e)
{
    if (S->top==0)
    {
        cout << "栈为空" << endl;
        return -1;
    }
    else
    {
      *e=S->stack[S->top-1];
      return 1;
    }
}

int PushStack(Stack * S, Datatype  e)
{
    if (S->top== StackSize)
    {
        cout << "栈满,不能入栈" << endl;
        return -1;
    }
    else
    {

         S->stack[S->top]=e;
         S->top++;
        return 1;
    }
}

int PopStack(Stack * S, Datatype * e)
{
    if (S->top==0)
    {
        cout << "栈为空,不能出栈" << endl;
        return -1;
    }
    else
    {
        S->top--;
        *e = S->stack[S->top];
        return 1;
    }
}

void ClearStack(Stack * S)
{
    S->top = 0;
}

测试函数:

int main() {
Stack S;
InitStack(&S);
Datatype a[]{'A','B','C','d'};
for (int i = 0; i <sizeof(a)/sizeof(a[0]); i++)
{
PushStack(&S, a[i]);
}
Datatype e;
cout << StackLength(S) << endl;
PopStack(&S,&e);
cout << e << endl;
cout << StackLength(S) << endl;
PopStack(&S, &e);
cout << e << endl;
cout << StackLength(S) << endl;
PopStack(&S, &e);
ClearStack(&S);
cout << StackLength(S) << endl;
cout << e << endl;
cout << StackLength(S) << endl;
PopStack(&S, &e);
cout << e << endl;
cout << StackLength(S) << endl;
PopStack(&S, &e);
cout << e << endl;
cout << StackLength(S) << endl;
system("PAUSE");
return 0;
}

测试结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值