stack.h
#pragma once
class Stack
{
public:
Stack(int stackSize);
int empty() const;
int size() const;
//特殊成员: const成员: 不能修改数据成员
protected:
int stackSize;
};
stack.cpp
#include "stack.h"
Stack::Stack(int stackSize)
{
this->stackSize = stackSize;
}
int Stack::empty() const
{
return stackSize==0;
}
int Stack::size() const
{
return stackSize;
}
node.h
#pragma once
class Node
{
public:
Node(int data);
Node(int data, Node* next);
Node* getNext();
int getData();
protected:
int data;
Node* next;
};
node.cpp
#include "node.h"
Node::Node(int data):data(data),next(nullptr)
{
}
Node::Node(int data, Node* next):data(data),next(next)
{
}
Node* Node::getNext()
{
return next;
}
int Node::getData()
{
return data;
}
liststack.h
#pragma once
#include "node.h"
#include "stack.h"
class ListStack :public Stack
{
public:
ListStack();
void push(int data);
void pop();
int top();
protected:
Node* headNode; //无头链表
};
liststack.cpp
#include "listStack.h"
ListStack::ListStack():Stack(0),headNode(nullptr)
{
}
void ListStack::push(int data)
{
headNode =new Node(data, headNode); //无表头链表的表插入
stackSize++;
}
void ListStack::pop()
{
if (empty())
return;
Node* nextNode = headNode->getNext();
delete headNode;
headNode = nextNode;
stackSize--; //忘记做的
}
int ListStack::top()
{
return headNode->getData();
}
common.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
arrayStack .h
#pragma once
#include "stack.h"
class ArrayStack :public Stack
{
public:
ArrayStack(int maxSize);
void push(int data);
void pop();
int top();
protected:
int* memory;
int maxSize;
};
arrayStack .cpp
#include "arrayStack.h"
ArrayStack::ArrayStack(int maxSize):Stack(0)
{
memory = new int[maxSize];
this->maxSize = maxSize;
}
void ArrayStack::push(int data)
{
if (stackSize == maxSize)
return;
memory[stackSize++] = data;
}
void ArrayStack::pop()
{
if (stackSize == 0)
return;
stackSize--;
}
int ArrayStack::top()
{
return memory[stackSize - 1];
}
C++写stack.cpp
#include "arrayStack.h"
#include "common.h"
#include "ListStack.h"
int main()
{
ArrayStack* pArrayStack = new ArrayStack(10);
for (int i = 0; i < 6; i++)
{
pArrayStack->push(i);
}
while (!pArrayStack->empty())
{
cout << pArrayStack->top() << "\t";
pArrayStack->pop();
}
cout << endl;
cout << pArrayStack->size() << endl;
//---------------------------------------------------
ListStack* pListStack = new ListStack;
for (int i = 0; i < 6; i++)
{
pListStack->push(i);
}
while (!pListStack->empty())
{
cout << pListStack->top() << "\t";
pListStack->pop();
}
cout << endl;
return 0;
}