考研复习之栈(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33094993/article/details/77603191

最简单的顺序栈:

#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;
}

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

猜你喜欢

转载自blog.csdn.net/qq_33094993/article/details/77603191