- //2014-5-27
- //liang
- //栈的链表实现
- #include <iostream>
- #include <cstdlib>
- typedef int T;
- using namespace std;
- class Stack
- {
- public:
- Stack():pHead(NULL),cnt(0){};
- void push(const T& d);
- void pop();
- int gettop();
- int empty(){return cnt==0;};
- int size(){return cnt;};
- private:
- typedef struct Node
- {
- T data;
- struct Node *pNext;
- }NODE,*PNODE;
- PNODE pHead;
- int cnt;
- };
- void Stack:: push(const T& d)
- {
- PNODE pNew=new NODE;
- pNew->data=d;
- if(pHead==NULL)
- {
- pHead=pNew;
- pNew->pNext=NULL;
- }
- else
- {
- pNew->pNext=pHead;
- pHead=pNew;
- }
- cnt++;
- }
- void Stack::pop()
- {
- if(empty())
- {
- cout << "栈为空" << endl;
- }
- PNODE p=pHead;
- while(p!=NULL)
- {
- cout << p->data << ' ';
- p=p->pNext;
- }
- cout << endl;
- delete p;
- }
- int Stack::gettop()
- {
- if(empty())
- {
- cout << "栈为空!" << endl;
- exit(-1);
- }
- else
- return pHead->data;
- }
- int main()
- {
- Stack s;
- s.push(1);
- s.push(2);
- s.push(3);
- s.push(4);
- s.push(5);
- s.pop();
- cout << "栈顶:" << s.gettop() << endl;
- cout << "栈的大小:" << s.size() << endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0611201410914.html
来源: http://www.codesnippet.cn/detail/0611201410914.html