1. | makenull (S) | creates an empty stack |
2. | top (S) | returns the element at the top of the stack. |
Same as retrieve (first (S), S) | ||
3. | pop (S) | deletes the top element of the stack |
Same as deletes (first (S), S) | ||
4. | push (x, S) | Insert element x at the top of stack S. |
Same as Inserts (x, first (S), S) | ||
5. | empty (S) | returns true if S is empty and false otherwise |
item-type info ;
struct node-tag * next ;
} node-type ;
typedef struct stack-tag {
node-type * top ;
} stack-type ;
stack-type stack ; /* define a stack */
stack-type * sp = & stack ; /* pointer to stack */
node-type *np ; /* pointer to a node */
/* makenode allocates enough space for a new node and initializes it */
node-type * makenode (item-type item)
{
node-type *p ;
if ((p = (node-type *) malloc (sizeof
(node-type))) = = null)
error (``exhausted memory'') ;
else {
p info = item ;
p next = null ;
}
return (p) ;
}
/* pushnode pushes a node onto the top of the linked stack */
void pushnode (node-type *np, stack-type *sp)
{
if (np = = null)
error (``attempt to push a nonexistent node'')
else {
np next = sp top ;
sp top = np
}
}
void popnode (node-type * *np ; stack-type *sp)
{
if (sp top = = null)
error (``empty stack'') ;
else {
*np = sp top ;
sp top = (* np) next ;
}
}
void push (item-type item ; stack-type *sp)
{
pushnode (makenode (item), sp) ;
}
/* pop-pop a node from the stack and return its item */
void pop (item-type * item, stack-type *sp)
{
node-type * np ;
popnode (& np, sp) ;
* item = np info ;
free (np) ;
}