栈的链式存储示意图:
栈的相关知识和顺序栈一样,实现过程和单链表一样。
代码:
#include<iostream>
using namespace std;
template<class T>
struct Node
{
T data;
Node<T>* next;
};
template<class T>
class stack
{
private:
Node<T>* top;
public:
stack()
{
top = NULL;
}
~stack()
{
while (top != NULL)
{
Node <T> *p;
p = top->next;
delete top;
top = p;
}
}
void push(T x)
{
Node<T>* s;
s = new Node<T>;
s->data = x;
s->next = top;
top = s;
}
void pop()
{
Node<T>* p;
p = top;
top = top->next;
delete p;
}
T getTop()
{
return top->data;
}
bool Empty()
{
if (top == NULL)
return true;
else
return false;
}
void print()
{
Node<T>* p;
p = top;
if(p!=NULL)
cout << p->data << " ";
while (p != NULL && p->next != NULL)
{
p = p->next;
cout << p->data << " ";
}
}
};
int main()
{
stack<int>s;
if (s.Empty())
cout << "Empty!!!" << endl;
else
cout << "Have element!" << endl;
s.push(1);
s.push(2);
s.push(3);
s.print();
if (s.Empty())
cout << "Empty!!!" << endl;
else
cout << "Have element!" << endl;
cout << endl;
s.pop();
s.print();
cout << s.getTop() << endl;
return 0;
}