











































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!












































































EE 232 Data Structures Session-18 , Spring- 2020
❑ A stack is a list with the restriction that insertions and deletions take place at the same end of the list according to the last-in-first-out (LIFO) principle. ❖ This end is called top ❖ The other end is called bottom A well-known example where we use a stack: ❖ Function calls
Example ❖ pile of plates 1 2 bottom top 1 2 3 bottom top 1 bottom top running time?
empty stack top A top push an element top push another A B top pop A
Common errors ❑ A Pop or Top on an empty stack is generally considered an error in the stack ADT. ❑ Running out of space when performing a Push is an implementation error but not an ADT error.
Linked List Implementation of Stacks ❖ Push is performed by inserting at the front of the list. ❖ Pop is performed by deleting the element at the front of list. ❖ Top operation returns the value of the element at the front. NULL Top of Stack We could use calls to the linked list routines of the previous section, but we will rewrite the stack routines from scratch for the sake of clarity.
Programming details ❖ Implementing the stack with a header #ifndef _Stack_h #define _Stack_h struct Node; typedef struct Node PtrToNode; typedef PtrToNode Stack; int IsEmpty( Stack S ); Stack CreateStack( void ); void DisposeStack( Stack S ); void MakeEmpty( Stack S ); void Push( ElementType X, Stack S ); ElementType Top( Stack S ); void Pop( Stack S ); #endif / _Stack_h */ struct Node { ElementType Element; PtrToNode Next; };
Programming details… Stack CreateStack( void ) { Stack S; S = malloc( sizeof( struct Node ) ); if( S == NULL ) FatalError( "Out of space!!!" ); S->Next = NULL; MakeEmpty( S ); return S; } Running time?
Programming details… void MakeEmpty( Stack S ) { if( S == NULL ) Error( "Must use CreateStack first" ); else while( !IsEmpty( S ) ) Pop( S ); } Running time?
Programming details… ElementType Top( Stack S ) { if( !IsEmpty( S ) ) return S->Next->Element; Error( "Empty stack" ); return 0; /* Return value used to avoid warning */ } Running time?
Programming details… void Pop( Stack S ) { PtrToNode FirstCell; if( IsEmpty( S ) ) Error( "Empty stack" ); else { FirstCell = S->Next; S->Next = S->Next->Next; free( FirstCell ); } } Running time?
Array Implementation of Stacks ❖ This implementation avoids pointers and is probably the more popular solution. ❖ We need to declare an array size ahead of time.
Array Implementation of Stacks… ❖ With each stack, TopOfStack is defined that stores the array index of the top of the stack