Stack
Introduction to Stacks
A Stack is a data structure with which stores the elements in the
reverse order.
Introduction to Stacks
Using stack we can perform the following operations:
– Add data, one item at a time, Push
– Access the data item on the top (other data items are hidden from
view), Top
– Remove and discard the data item on the top, thus exposing the
next item which now becomes the top item, Pop.
The order in which data is added ("pushed"), accessed and
removed ("popped") is LIFO (last in, first out).
Stacks can be implemented based on arrays or linked lists.
Applications of stacks
Reversing Data: We can use stacks to
reverse data. (example: files, strings). Very
useful for finding palindromes.
Backtracking : Stacks can be used to
backtrack to achieve certain goals.
Function calls: Perhaps the most important
application of stacks is to implement function
calls. Most compilers implement function
calls by using a stack.
Applications of stacks
Arithmetic expression evaluation:
– An important application of stacks is in parsing.
– In high level languages, infix notation cannot be used to
evaluate expressions.
– A common technique is to convert a infix notation into
postfix notation, then evaluating it.
Operations on Stack
Implementation of stack
In the array implementation, we would:
– Declare an array of fixed size (which determines the
maximum size of the stack).
– Keep a variable which always points to the “top” of the
stack.
In the linked list implementation, we would:
– Maintain the stack as a linked list.
– A pointer variable top points to the start of the list.
– The first element of the linked list is considered as the
stack top.
Declaration
#define MAXSIZE 100
int st[MAXSIZE];
int top;
Stack Creation
void create ()
{
top = -1;
Top is a pointer holds the recently inserted
element within it.
Pushing an element into the stack
(Array)
PUSH
Pushing an element into the stack
(Array)
void push (int element)
{
if (top == (MAXSIZE-1))
{
printf(“\n Stack overflow”);
exit(1);
}
else
{
top ++;
st[top] = element;
}
}
Popping an element from the stack
(Array)
POP
Popping an element from the stack
(Array)
int pop ()
{
if (top == -1)
{
printf(“\n Stack underflow”);
exit(-1);
}
else
{
return (st[top--]);
}
}
Checking for stack empty
int isempty()
{
if (top == -1)
return 1;
else
return
(0);
}
Checking for stack full (Array)
int isfull()
{
if (top == (MAXSIZE–1))
return 1;
else
return 0;
}