链式栈
stack.h
#ifndef STACK_H_ #define STACK_H_ typedef int data_type; enum STACK_OP { STACK_ERR = -1, STACK_OK, STACK_EMPTY }; class STACK { private: data_type data; STACK *next; public: STACK(); STACK(data_type data); ~STACK(); data_type getData() const; STACK *getNext() const; void setData(data_type data); void setNext(STACK *next); int Push(STACK *pStack, data_type tData); int Pop(STACK *pStack, data_type *pData); int IsEmpty(STACK *pStack); void operator delete(void *pStack); }; #endif /* STACK_H_ */
stack.cpp
#include "STACK.h" #include <iostream> using namespace std; STACK::STACK(data_type data) { // TODO Auto-generated constructor stub this->setData(data); this->setNext(NULL); cout<<"STACK(data)"<<endl; } STACK::STACK() { // TODO Auto-generated constructor stub this->setData(0); this->setNext(NULL); cout<<"STACK"<<endl; } STACK::~STACK() { // TODO Auto-generated destructor stub cout<<"~STACK"<<endl; } data_type STACK::getData() const { return data; } STACK *STACK::getNext() const { return next; } void STACK::setData(data_type data) { this->data = data; } void STACK::setNext(STACK *next) { this->next = next; } int STACK::Push(STACK *pStack, data_type tData) { if (!pStack) return STACK_ERR; STACK *New = new STACK(tData); if (!New) return STACK_ERR; New->setNext(pStack->getNext()); pStack->setNext(New); return STACK_OK; } int STACK::Pop(STACK *pStack, data_type *pData) { if ((!pStack) || (!pData)) return STACK_ERR; STACK *Tmp = pStack->getNext(); if (!Tmp) { cout << "pop over" << endl; return STACK_ERR; } *pData = Tmp->getData(); pStack->setNext(Tmp->getNext()); Tmp->setNext(NULL); delete Tmp; return STACK_OK; } int STACK::IsEmpty(STACK *pStack) { if (!pStack) return STACK_ERR; if (!pStack->getNext()) return STACK_EMPTY; return STACK_OK; } void STACK::operator delete(void *pStack) { if (!pStack) return; STACK *Tmp = ((STACK *)pStack)->getNext(); while(Tmp){ ((STACK *)pStack)->setNext(Tmp->getNext()); free(Tmp); Tmp = ((STACK *)pStack)->getNext(); } free(pStack); return; }
main.cpp
#include "STACK/STACK.h" #include <iostream> using namespace std; void function() { STACK *pStack = new STACK; int *data = new int[5]; int pdata; int i; for (i = 4; i >= 0; i--) { data[i] = i; } for (i = 5; i >= 0; i--) { pStack->Push(pStack, i); cout << i << " "; } cout << endl; for (i = 5; i >= 0; i--) { pStack->Pop(pStack, &pdata); cout << pdata << " "; } cout << endl; pStack->Push(pStack, 9); pStack->Pop(pStack, &pdata); cout << pdata << " "; pStack->Push(pStack, 5); pStack->Push(pStack, 3); pStack->Push(pStack, 7); pStack->Pop(pStack, &pdata); cout << pdata << " "; pStack->Push(pStack, 0); pStack->Pop(pStack, &pdata); cout << pdata << " "; pStack->Pop(pStack, &pdata); cout << pdata << " "; pStack->Pop(pStack, &pdata); cout << pdata << " " << endl; delete pStack; } int main() { function(); return 0; }
时间: 2024-12-17 12:35:00