Stack notes (3) -- chain stack, notes --
Chain Stack: The chain table is used as the storage structure stack. For ease of operation, a single-chain table with the leading node is generally used.
The head pointer of the linked list acts as the top pointer of the stack.
The structure of the chain stack is defined as follows:
Typedef struct node
{
StackElementType data;
Stuct node * next;
} LinkStackNode;
Typedef LinkStackNode * LinkStack;
Stack-to-stack operations
Int Push (LinkStack top, StackElementType x)
{
LinkStackNode * temp;
Temp = (LinkStackNode *) malloc (sizeof (LinkstackNode ));
If (temp = NULL)
Return (FALSE); // An error occurred while applying for a space.
Temp-> data = x;
Temp-> next = top-> next;
Top-> next = temp; // modify the elements at the top of the current stack
Return (TRUE );
}
Chain stack out-of-stack operations
Int Pop (LinkStack top, StackElementType * x)
{
LinkStackNode * temp;
Temp = top-> next;
If (temp = NULL)
Return (FALSE); // stack is empty
Top-> next = temp-> next;
* X = temp-> data;
Free (temp); // release the bucket
Return (TRUE );
}
Multiple Single-Chain tables can be used to implement multiple chain stacks (put the top pointer of multiple chain stacks in a one-dimensional pointer array for unified management)
The definition structure is as follows:
# Define M 10 // suppose 10 chain stacks are defined
Typedef stuct node
{
StackElementType data;
Struct node * next;
} LinkStackNode * LinkStack;
LinkStack top [M];
Stack-in Operation
Int pushi (LinkStack top [M], int I, StackElementType x)
{
LinkStackNode * temp;
Temp = (LinkStackNode *) malloc (sizeof (LinkStackNode ));
If (temp = NULL)
Return (FALSE );
Temp-> data = x;
Temp-> next = top [I]-> next;
Top [I]-> next = temp;
Return (TRUE );
}
Stack element I
Int Pop (LinkStack top [M], int I, StackElementType * x)
{
LinkStackNode * temp;
Temp = top [I]-> next;
If (temp = NULL)
Return (FALSE );
Top [I]-> next = temp-> next;
* X = temp-> data;
Free (temp); // release the bucket
Return (TRUE );
}