vc++栈的简单实现
栈的数据类型是先进后出
1 #ifndef __MYSTACK__ 2 #define __MYSTACK__ 3 #include <Windows.h> 4 typedef struct Node 5 { 6 int data; //数据 7 Node* next; //下一个节点 8 }NODE,*PNODE; 9 class Stack 10 { 11 public: 12 Stack(); 13 ~Stack(); 14 public: 15 int pop(); //返回这个出栈的数据 16 BOOL push(int pS); //接收入栈的数据 17 BOOL empty(); //判断栈是否是null 如果是null返回TRUE 18 int treaverse(); //遍历所有数据 19 20 private: 21 PNODE m_pTop; //栈顶 22 PNODE m_pBottom; //栈底 23 }; 24 Stack::Stack() 25 { 26 m_pTop = new NODE; 27 if(!m_pTop)return; 28 m_pTop->next = NULL; //下一个节点等于null 29 m_pBottom = m_pTop; 30 } 31 Stack::~Stack() 32 { 33 //析构 34 if (empty()) 35 { 36 delete m_pTop; 37 }else 38 { 39 PNODE p = m_pTop; 40 while (p!=m_pBottom) 41 { 42 p = m_pTop->next; 43 delete m_pTop; 44 m_pTop = p; 45 } 46 delete m_pBottom; 47 } 48 49 50 } 51 int Stack::push(int pS) 52 { 53 PNODE pNext = new NODE; 54 if(!pNext)return -1; 55 ZeroMemory(pNext,sizeof(NODE)); 56 pNext->data = pS; //传进来的参数 57 pNext->next = m_pTop; 58 m_pTop = pNext; 59 return true; 60 } 61 BOOL Stack::empty() 62 { 63 if (m_pTop == m_pBottom) 64 return true; 65 else 66 return false; 67 } 68 int Stack::pop() 69 { 70 int temp = NULL; 71 if (empty()) 72 return -1; 73 PNODE p = m_pTop->next; 74 temp = m_pTop->data; //获取到的数据 75 delete m_pTop; 76 m_pTop = p; 77 return temp; 78 } 79 int Stack::treaverse() 80 { 81 if(empty())return -1; 82 PNODE p = m_pTop; 83 while(p!=m_pBottom) 84 { 85 printf("%d\r\n",p->data); 86 p = p->next; 87 } 88 } 89 #endif //__MYSTACK__