数据结构(2) -- 堆栈
1、顺序存储
//栈的顺序存储实现 //Stack.h #ifndef STACK_H_ #define STACK_H_ #define ElementType int #define MaxSize 100 typedef struct _Node { ElementType data[MaxSize]; int top; }Node; class Stack { private: Node data; public: Stack(); ~Stack(); int IsFull(); void Push(ElementType item); int IsEmpty(); ElementType Pop(); }; #endif //Stack.cpp #include "Stack.h" #include <iostream> Stack::Stack() { data.top = -1; } Stack::~Stack() { } int Stack::IsFull() { if (data.top == (MaxSize - 1)) return 1; else return 0; } void Stack::Push(ElementType item) { if (IsFull() == 1) { std::cout << "栈溢出" << std::endl; return; } data.data[++(data.top)] = item; } int Stack::IsEmpty() { if (data.top == -1) return 1; else return 0; } ElementType Stack::Pop() { if (IsEmpty()) std::cout << "栈已空" << std::endl; return data.data[(data.top)--]; }
2、链式存储
//栈的链式存储实现 //PStack.h #ifndef PSTACK_H_ #define PSTACK_H_ #define ElementType int #define MaxSize 100 typedef struct _PNode { ElementType data; _PNode* next; }PNode; class PStack { private: PNode *top; public: PStack(); ~PStack(); int IsFull(); void Push(ElementType item); int IsEmpty(); ElementType Pop(); }; #endif //PStack.cpp #include "PStack.h" #include <iostream> PStack::PStack() { top = new PNode(); top->next = NULL; } PStack::~PStack() { delete top; } void PStack::Push(ElementType item) { PNode* s = new PNode(); s->data = item; s->next = top; top = s; } int PStack::IsEmpty() { if (top == NULL) return 1; else return 0; } ElementType PStack::Pop() { if (IsEmpty()) std::cout << "栈已空" << std::endl; PNode *s; s = top; ElementType e = s->data; top = top->next; delete s; return e; }
3、测试样例
#include <iostream> #include "PStack.h" using namespace std; int main() { PStack st; st.Push(5); st.Push(6); st.Push(2); int a = st.Pop(); int b = st.Pop(); cout << "a , b" << a << " " << b << endl; st.Push(b / a); a = st.Pop(); b = st.Pop(); cout << "a , b" << a << " " << b << endl; st.Push(b + a); st.Push(3); st.Push(4); a = st.Pop(); b = st.Pop(); cout << "a , b" << a << " " << b << endl; st.Push(b * a); a = st.Pop(); b = st.Pop(); st.Push(b - a); cout << "a , b" << a << " " << b << endl; cout << "根据后缀表达是计算5+6/2-3*4的值为:" << st.Pop() << endl; system("pause"); return 0; }