When a single linked list is limited to insert and delete operations on the head, that is, the chain stack, we will be a single linked list of the head pointer and stack top of the stack pointer to one, usually for the chain stack, is not required head node, because we maintain the top of the stack pointer. For the chain stack, there is basically no stack full situation, unless the memory has no space to use, for the empty stack, the original definition of the list is the head pointer to null, then the chain stack of empty is actually top = = null.
Sample code: (Adapted from the "Liar Data Structure")
#include <iostream> using namespace std;
typedef int ELEMTYPE;
typedef struct NODE {elemtype data;
struct Node *next;
Node, *nodeptr;
typedef struct LINKSTACK {nodeptr top;//stack head pointer int count;//element number} Linkstack;
/* Constructs an empty stack */bool Initstack (Linkstack *ps) {cout << "Init stack ..." << Endl;
Ps->top = NULL;
Ps->count = 0;
return true;
/* Set to empty stack/bool Clearstack (Linkstack *ps) {cout << "clear stack ..." << Endl;
if (ps->top = NULL) return true;
Nodeptr p = ps->top;
NODEPTR Q;
while (p) {q = p->next;
Free (p);
p = q;
} ps->top = NULL;
Ps->count = 0;
return true;
BOOL Stackempty (Linkstack LS) {return ls.count = = 0;}
int Stacklength (Linkstack LS) {cout << "Stack Length:";
return ls.count;
/* Returns the top element of the stack */bool GetTop (Linkstack LS, Elemtype *pe) {*pe = ls.top->data; CouT << "get top Item" << *pe << Endl;
return true;
} * * Press stack/BOOL push (Linkstack *ps, Elemtype Elem) {cout << "Push Item" << Elem << Endl;
Nodeptr s = (nodeptr) malloc (sizeof (Node));
S->data = Elem;
S->next = ps->top;
Ps->top = s;
ps->count++;
return true;
}/* out stack/bool Pop (Linkstack *ps, Elemtype *pe) {nodeptr p = ps->top;
*pe = p->data;
Ps->top = p->next;
Free (p);
ps->count--;
cout << "Pop Item" << *pe << Endl;
return true;
}/* Output stack element/bool Stacktraverse (Linkstack LS) {cout << "stack Traverse ..." << Endl;
Nodeptr p = ls.top;
while (P!= NULL) {cout << p->data << ';
p = p->next;
} cout << Endl;
return true;
int main (void) {Linkstack LS;
Initstack (&LS);
for (int i = 0; i < 5; i++) Push (&ls, i); Stacktraverse (LS);
int result;
GetTop (LS, &result);
POPs (&ls, &result);
Stacktraverse (LS); if (!
Stackempty (LS)) cout << stacklength (LS) << Endl;
Clearstack (&LS);
Stacktraverse (LS);
return 0; }
The output is:
If the use of the stack element changes unpredictable, sometimes very small, sometimes very large, then it is best to use the chain stack, conversely, if the change in the controllable range, it is recommended to use a sequential stack will be better.