栈的链表实现
本想回答一个小伙伴的提问,结果没注意问题已经关闭。贴在这里吧,如果有学些栈的新同学可以参考下。
程序代码:
//stack struct StackNode{ void* pData; StackNode* pNext; }; typedef void (*FN_OutputNode)(void* pNode); class Stack{ public: Stack(FN_OutputNode fnOutput); ~Stack(); void push(void* pData); void* pop(); void outputAll(); private: StackNode* m_pTop; FN_OutputNode m_fnOutput; }; Stack::Stack(FN_OutputNode fnOutput) { m_fnOutput=fnOutput; m_pTop=NULL; } void Stack::push(void* pData) { StackNode* pNode = new StackNode(); pNode->pData=pData; pNode->pNext = m_pTop; // link as head of old list m_pTop=pNode;//update list head } void* Stack::pop() { if(NULL == m_pTop) { return m_pTop; } StackNode* pNode = m_pTop; m_pTop = m_pTop->pNext; void* pData = pNode->pData; delete pNode; return pData; } void Stack::outputAll() { if(NULL == m_fnOutput) { return; } StackNode* pNode= m_pTop;// last one is output first while(pNode != NULL) { m_fnOutput(pNode->pData); pNode=pNode->pNext; } } Stack::~Stack() { StackNode* pNode=m_pTop; while(pNode != NULL) { m_pTop=pNode->pNext;//update head to next delete pNode;// pNode->pData is managed by user of Stack class pNode= m_pTop;// the node to release } } void myoutput(void* p) { printf((char*)p); printf("\r\n"); } int _tmain(int argc, _TCHAR* argv[]) { Stack s(myoutput); s.push("hi"); s.push("how are you?"); s.push("I am fine."); s.outputAll(); Stack* pStack = new Stack(myoutput); pStack->push("hi"); pStack->push("how are you????"); pStack->push("I am fine."); pStack->outputAll(); delete pStack; return 0; }