一、用数组实现
头文件stack.h:
#ifndef STACK_H
#define STACK_H
class Stack
{
public:
Stack(int maxSize);
~Stack();
bool isEmpty();
bool isFull();
bool Top(int &x);
bool push(int x);
bool pop();
void clear();
private:
int maxTop;
int top;
int *s;
};
#endif // STACK_H
stack.cpp
#include "stack.h"
#include <iostream>
using namespace std;
Stack::Stack(int maxSize)
{
maxTop = maxSize;
top = -1;
s = new int[maxSize];
}
Stack::~Stack()
{
delete []s;
}
bool Stack::isEmpty()
{
return top == -1;
}
bool Stack::isFull()
{
return top == maxTop;
}
bool Stack::Top(int &x)
{
if(isEmpty()){
cout<<"Empty"<<endl;
return false;
}
x = s[top];
return true;
}
bool Stack::push(int x)
{
if(isEmpty()){
cout<<"Empty"<<endl;
return false;
}
s[++top] = x;
return true;
}
bool Stack::pop()
{
if(isEmpty()){
cout<<"Empty"<<endl;
return false;
}
cout<<s[top]<<" poped!"<<endl;
top--;
return true;
}
测试:
#include <QCoreApplication>
#include <iostream>
using namespace std;
#include "stack.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Stack s(5);
s.push(3);
s.push(2);
s.push(1);
s.push(4);
return a.exec();
}
二、用链表实现
头文件stack.h
#ifndef PTSTACK_H
#define PTSTACK_H
#include <iostream>
using namespace std;
class Node
{
public:
Node();
Node(int e);
private:
int element;
Node *link;
friend class ptStack;
};
class ptStack
{
public:
ptStack(int maxSize);
~ptStack();
bool isEmpty();
bool isFull();
bool push(int e);
bool pop();
bool getTop(int &x);
int getLength();
private:
int maxTop;
int count;
Node *Top;
};
#endif // PTSTACK_H
stack.cpp:
#include "ptstack.h"
#include <iostream>
using namespace std;
ptStack::ptStack(int maxSize)
{
maxTop = maxSize;
Top = NULL;
count = 0;
}
ptStack::~ptStack()
{
for(int i = 0;i < count;i++){
Node *p = Top;
Top = p->link;
delete p;
}
}
bool ptStack::isEmpty()
{
return count == 0;
}
bool ptStack::isFull()
{
return count == maxTop;
}
bool ptStack::push(int e)
{
if(isFull()){
cout<<"The stack if full!"<<endl;
return false;
}
Node *newNode = new Node(e);
if(isEmpty()){
Top = newNode;
}
else{
newNode->link = Top;
Top = newNode;
}
cout<<e<<" has been pushed!"<<endl;
count++;
return true;
}
bool ptStack::pop()
{
if(isEmpty()){
cout<<"The stack is empty!"<<endl;
return false;
}
Node *p = Top;
Top = p->link;
cout<<p->element<<" has been poped!"<<endl;
delete p;
count--;
return true;
}
bool ptStack::getTop(int &x)
{
if(isEmpty()){
cout<<"The stack is empty!"<<endl;
return false;
}
Node *temp = Top;
x = temp->element;
return true;
}
int ptStack::getLength()
{
return count;
}
Node::Node()
{
link = NULL;
element = 0;
}
Node::Node(int e)
{
link = NULL;
element = e;
}
测试:
#include <QCoreApplication>
#include <iostream>
using namespace std;
#include "ptstack.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ptStack s(5);
s.push(3);
s.push(6);
s.push(1);
s.pop();
return a.exec();
}