STACK
IMPLEMENTATION
REVIEW:
It is an abstract data structure
Can implemented with a storage data structure :
array and linked list
top is the parameter associated with stack
Basic operations:
isEmpty() : if there is no element in the stack
isFull(): if the stack is full
push(): insert an element into the stack
pop(): delete an element from the stack
peek(): return the value at the top of the stack
push() Algorithm
pop() Algorithm
Implementing Stacks: Array
Advantages
best performance
Disadvantage
fixed size
Basic implementation
initially empty array
field to record where the next data gets placed
into
if array is full, push() returns false
otherwise adds it into the correct spot
if array is empty, pop() returns null
otherwise removes the next item in the stack
Stack : isEmpty()
int isEmpty()
{
if (s.top == -1)
return 1;
else
return 0;
}
Stack : isFull()
int isFull()
{
if (st.top >= size - 1)
return 1;
else
return 0;
}
Stack : void push()
/*Function to add an element to the stack*/
void push()
{
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Error: Overflow\n");
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
}
Stack : void pop()
/*Function to delete an element from the stack*/
void pop ()
{
int num;
if (s.top == - 1)
{
printf ("Error: Stack Empty\n");
}
else
{
num = s.stk[s.top];
printf ("poped element is = %d\n", num);
s.top = s.top - 1;
}
}
Implementing a Stack: Linked
List
Advantages:
always constant time to push or pop an
element
can grow to an infinite size
Disadvantages
the common case is the slowest of all the
implementations
can grow to an infinite size
Basic implementation
list is initially empty
push() method adds a new item to the head of
the list
pop() method removes the head of the list
Stack Applications
Stacks are a very common data
structure
compilers
parsing data between delimiters (brackets)
operating systems
program stack
virtual machines
manipulating numbers
pop 2 numbers off stack, do work (such as add)
push result back on stack and repeat
artificial intelligence
finding a path