Lecture7 Stacks
Lecture7 Stacks
Data Structures
Stacks
Stacks in real life: stack of books, stack of
plates
Add new items at the top
Remove an item at the top
Stack data structure similar to real life:
collection of elements arranged in a linear
order.
Can only access element at the top
What are Stacks?
In array insertion and deletion can take place at
both end, i.e. start and end,
But if insertion and deletion are restricted from one
end, must used STACKS and QUEUES.
?
Pop Peek
Empty
?
Stack Operations
Push(X) – insert X as the top element of
the stack
Pop() – remove the top element of the
stack and return it.
Top() – return the top element without
removing it from the stack.
Stack Operations
top 1
top 7 7
top 5 5 5
top 2 2 2 2
push(2) push(5) push(7) push(1)
top 21
top 7 7 top 7
5 5 5 top 5
2 2 2 2 top 2
1 pop() push(21) 21 pop() 7 pop() 5 pop()
Operations on Stack
A stack is generally implemented
with only two principle operations:
Push: adds an item to a stack
Pop: extracts the most recently
pushed item from the stack
Other methods such as
top: returns the item at the top
without removing it
IsEmpty: determines whether the
stack has anything in it
IsFull: determines whether the stack
is full or stacksize is reached to
MAXST anything in it
Stack Operation
The last element to go into the stack is
the first to come out: LIFO – Last In First
Out.
What happens if we call pop() and there is
no element?
Have IsEmpty() boolean function that
returns true if stack is empty, false
otherwise.
Algorithms of Push Operation
Push (STACK , TOP, MAXST, ITEM)
Algorithm for push element into the Stack
top 1
2 5 7 1
7
5 0 1 2 3 4
2 top = 3
Stack using an Array
In case of an array, it is possible that the
array may “fill-up” if we push enough
elements.
Have a boolean function IsFull() which
returns true is stack (array) is full, false
otherwise.
We would call this function before calling
push(x).
Stack Operations with Array
int pop()
{
return A[current--];
}
void push(int x)
{
A[++current] = x;
}
Stack Operations with Array
int top()
{
return A[current];
}
int IsEmpty()
{
return ( current == -1 );
}
int IsFull()
{
return ( current == size-1);
}
A quick examination shows that all five
operations take constant time.
Stack Using Linked List
We can avoid the size limitation of a stack
implemented with an array by using a
linked list to hold the stack elements.
As with array, however, we need to decide
where to insert elements in the list and
where to delete them so that push and
pop will run the fastest.