C++栈-顺序存储

SqStack.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 10

class SqStack
{
private:
int data[MAXSIZE];
int base, top;
public:
SqStack();
SqStack(int array[], int n);

int GetTop(); // 获取栈顶元素

void Push(int e); // 入栈,通过e返回数据
bool Pop(int& e); // 出栈

void ShowAll(); // 头为栈底,尾为栈顶
};

SqStack.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "SqStack.h"

SqStack::SqStack()
{
top = base = -1;
}

SqStack::SqStack(int array[], int n)
{
top = base = -1;
for (int i = 0; i < n; i++)
Push(data[i]);
}

void SqStack::Push(int e)
{
if ((top + 1) < MAXSIZE)
{
top = top + 1;
data[top] = e;
}

if (base == -1) // 表示空栈第一次入栈
base = 0;
}

bool SqStack::Pop(int& e)
{
if (base == -1)// 空栈
return false;

if (top >= 0)
{
e = data[top];
top = top - 1;
}

if (top == -1)
base == -1;
return true;
}

void SqStack::ShowAll()
{
for (int i = 0; i <= top; i++)
cout << data[i] << " ";
cout << endl;
}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>	
using namespace std;

#include"SqStack.h"

int main()
{

SqStack stack;

stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.ShowAll();
int e;
stack.Pop(e);
stack.Pop(e);
stack.Pop(e);
stack.ShowAll();
stack.Pop(e);
stack.Pop(e);// 当栈为空时,此时出栈是否会报错

stack.ShowAll();
cout << endl;


return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!