Objectives of this lecture
Review
Dynamic Implementation of Stack.
/* file name: stack.h */
typedef
... StackEntry;
typedef
struct node {
StackEntry
entry;
struct node *next;
} Node;
typedef
struct {
Node *top;
}
Stack;
void
Pop(StackEntry *item, Stack *s);
void
Push(StackEntry item, Stack *s);
Boolean
StackEmpty(Stack *s);
Boolean
StackFull();
void
CreateStack(Stack *s);
void
ClearStack(Stack *);
/*
File name: stack.c */
#include
"common.h" /*you must include
stdlib.h in common.h
#include
"stack.h"
Node
*MakeNode(StackEntry item);
/*
Push: make a new node with item and push it onto stack.
Pre: The stack exists and has been initialized.
Post:
The argument item has been stored at the top of the stack.
*/
void
Push(StackEntry item, Stack *s)
{ Node *np = MakeNode(item);
if (np == NULL)
Error("Attempted to push a
non-existing node.");
else
{
np->next = s->top;
s->top = np;
}
}
/*
Pop: pop a node from the stack and return its item.
Pre: The stack exists and is not empty.
Post:
The item at the top of stack has been removed and returned.
*/
void
Pop(StackEntry *item, Stack *s)
{
Node *np;
if (s->top == NULL)
Error("Empty stack.");
else
{
np = s->top;
s->top = np->next;
*item = np->entry;
free(np);
}
}
/*
StackEmpty: return non-zero if the stack is empty.
Pre: The stack exists and has been initialized.
Post:
Return non-zero if the stack is empty; return zero, otherwise.
*/
Boolean
StackEmpty(Stack *s)
{ return s->top == NULL;
}
/*
StackFull: always return FALSE because it is a linked stack.
Pre: The stack exists and has been initialized.
Post:
Return FALSE.
*/
Boolean
StackFull(void)
{
Node *np;
if ((np = (Node *) malloc(sizeof(Node))) ==
NULL)
return (TRUE);
else
{
free(np);
return (FALSE);
}
}
/*
CreateStack: initialize the stack to NULL.
Pre: None.
Post:
The stack has been initialized to be empty.
*/
void
CreateStack(Stack *s)
{
s->top = NULL;
}
/*
Pre: The stack s has been created.
Post:
All nodes in s have been destroyed and s is empty.
Uses:
None.
*/
void
ClearStack(Stack *s)
{
Node *np, *fp;
np=s->top;
while (np != NULL)
{
fp = np;
np = np->next;
free(fp);
}
}
/*
MakeNode: make a new node and insert item.
Pre: None.
Post:
Create a new node and insert item in it.
*/
Node
*MakeNode(StackEntry item)
{
Node *nodepointer;
if
((nodepointer = (Node *) malloc(sizeof(Node))) == NULL)
Error("Exhausted memory.");
else
{
nodepointer->entry = item;
nodepointer->next = NULL;
}
return nodepointer;
}
Exercises: