栈是先进后出的特殊线性表,只允许在表的末端进行插入和删除,后面将介绍两种实现栈的方式,分别是基于数组的实现、基于链表的实现。
栈的抽象定义
class Mystack
{
public:
Mystack() {}
virtual void push(int &x) = 0;
virtual bool pop(int &x) = 0;
virtual bool Top(int &x) const = 0;
virtual bool IsEmpty()const = 0;
virtual bool IsFull()const = 0;
virtual int getSize()const = 0;
};
顺序栈-----------使用数组表示栈空间
定义:
#pragma once
#include "Mystack.h"
#include <iostream>
#include <assert.h>
using namespace std;
const int stackIncreament = 20;
class SeqStack : public Mystack
{
public:
SeqStack(int sz = 50);
~SeqStack() { delete[]elements; }
void push(int &x);
bool pop(int &x);
bool Top(int &x);
bool IsEmpty()const {
return (top == -1) ? true : false;
}
bool IsFull()const {
return (top == maxSize - 1) ? true : false;
}
int getSize()const {
return top + 1;
}
void MakeEmpty() {
top = -1;
}
friend ostream& operator<<(ostream& os, SeqStack& s);
private:
int *elements;
int top;
int maxSize;
void overflowProcess();
};
实现:
#include "SeqStack.h"
SeqStack::SeqStack(int sz):top(-1),maxSize(sz)
{
elements = new int[maxSize];
assert(elements == NULL);
}
void SeqStack::push(int & x)
{
if(IsFull() == true){
overflowProcess();
}
elements[++top] = x;
}
bool SeqStack::pop(int & x)
{
if (IsEmpty() == true) {
return false;
}
x = elements[top--];
return true;
}
bool SeqStack::Top(int & x)
{
if (IsEmpty() == true) {
return false;
}
x = elements[top];
return true;
}
ostream& operator<<(ostream& os, SeqStack& s) {
os << "top = " << s.top << endl;
for (int i = 0; i <= s.top; ++i) {
os << i << ": " << s.elements[i] << endl;
}
return os;
}
void SeqStack::overflowProcess()
{
int *Newelement = new int[maxSize + stackIncreament];
if (Newelement == NULL) {
cout << "分配内存失败";
exit(1);
}
for (int i = 0; i <= top; ++i) {
Newelement[i] = elements[i];
}
delete[] elements;
elements = Newelement;
}
|