The Stack
The Stack
top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D) top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
Pop ()
top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D)
Pop ()
Pop ()
Pop ()
top
Stack
• Fundamental operations on a stack are Push,
which is equivalent to insert & Pop which is
equivalent to deletion.
Push (S, A)
Push (S, B)
Push (S, C)
Push (S, D) top
Pop ()
Pop ()
Pop ()
Pop ()
Stack
• Push by inserting at the front of the list.
• Pop by deleting the element at the front of
the list.
• Top examines the element at the front of the
list and returns its value.
Stack Operations
• struct Node
• {
– ElementType Element;
– Struct Node *Next;
• }
Stack Operations
• struct Node;
• typedef struct Node *PtrToNode;
• typedef PtrToNode Stack; // S
Push Operation
S
Push Operation
TmpCell
TmpCell
TmpCell
PtrToNode TmpCell = malloc (sizeof(struct Node));
TmpCell Element = “B”;
Push Operation
TmpCell
PtrToNode TmpCell = malloc (sizeof(struct Node));
TmpCell Element = “B”;
TmpCell Next = S Next;
S Next = TmpCell;
Push Operation
• void Push(ElementType X, Stack S)
• {
– PtrToNode TmpCell = malloc(sizeof(struct Node));
– if (TmpCell == NULL)
– {
• FatalError (“Out of Space!”);
– }
– else
– {
• TmpCellElement = X;
• TmpCellNext = SNext;
• SNext = TmpCell;
– }
• }
Stack Operations
• int IsEmpty(Stack S)
• {
– return SNext == NULL;
• }
Stack Operations
• ElementType Top(Stack S)
• {
– if (!IsEmpty(S))
–{
• return SNextElement;
–}
– return 0;
• }
Stack Operations
• void Pop(Stack S)
• {
– PtrToNode FirstCell;
– if (!IsEmpty(S))
– {
• Error(“Empty Stack”);
– }
– else
– {
– FirstCell = SNext;
– SNext = SNextNext;
– Free(FirstCell);
– }
• }
Stack Operations
• void MakeEmpty(Stack S)
• {
– while ( !IsEmpty(S))
–{
• Pop(S);
–}
• }
Array Implementation of Stack
• Associated with each stack is TopOfStack, which
is -1 for an empty stack.
• To push some element X onto the stack. We
increment TopOfStack and then set
Stack[TopOfStack] = X.