1. 程式人生 > >考研複習之棧(一)

考研複習之棧(一)

最簡單的順序棧:

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

測試結果:
這裡寫圖片描述