Chain Stack is implemented with a linked list, it is stored in memory is not continuous , and the number of nodes stored is variable, can be inserted or deleted according to the actual situation. This makes it more reasonable to take advantage of memory resources, making programs more flexible and less memory overhead.
The difference between a chain stack and a linked list is:
(1) Chain stack without head node, linked list in order to unify the empty table and non-empty table operation to join the head node
(2) Chain stack without head pointer and tail pointer
(3) The elements in the stack are limited, the user can only access the top of the stack
The LinkStack.h file code is as follows:
#include <iostream> using namespace std;
Template <class t> class Linkstacknode {public:t data;
Linkstacknode<t>* Next;
Linkstacknode (t& D): Data (d), next (NULL) {}};
Template <class t> class Linkstack {public:linkstack (): Top (NULL) {} ~linkstack ();
void push (t& value);
t& GetTop ();
T pop ();
BOOL IsEmpty ();
private:linkstacknode<t> * TOP;
};
Template <class t> linkstack<t>::~linkstack () {delete top;} Template <class t> void linkstack<t>::p ush (t& value) {linkstacknode<t>* AddNode = new Linkstacknod
E<t> (value);
Addnode->next = top;
top = AddNode;
} template <class t> t& linkstack<t>::gettop () {return top->data;}
Template <class t> t linkstack<t>::p op () {T value = top->data;
linkstacknode<t>* p = top;
top = top->next;
Delete p;
return value; } template <class t> bool Linkstack<t>::isempty () {return top = =NULL; }
The Main.cpp code is as follows:
#include "LinkStack.h"
using namespace std;
int main (int argc, char const *argv[])
{/
* code */
linkstack<int> s;
int i;
for (i = 0; i < 5; ++i) {
s.push (i);
}
cout << s.gettop () << Endl;
for (i = 0; i < 3; i++)
{
cout << s.pop () << Endl;
}
cout << s.gettop () << Endl;
return 0;
}