Unit 2 Stacks and Queues
Unit 2 Stacks and Queues
Unit 2 Stacks and Queues
1.Introduction,Stack as ADT
2. Representation and implementation of stack using sequential and
linked allocation
3. Queue as ADT
4. Representation and implementation of Queue using sequential
and linked allocation
5.Circular queue and its implementation
6.Application of stack for expression evaluation
and expression conversion,
7.Recursion, priority queue
Introduction
• A stack is a basic data structure, it’s defined as an ordered collection of
elements represented by a real physical stack.
• Linear data structure features insertion and deletion of items take place at one
end called top of the stack.
• Therefore, In these structure data set as a stack of books or plates, in the
stack, you can remove the item from the top order. you can use these
concepts or structures all throughout programming. the implementation of the
stack also know as LIFO (Last in First Out)
• these are the three basic concepts that can be performed on stacks.
1) push (insert the items into a stack)
2) Pop (delete an item from the stack)
Algorithm for Push and Pop Function
• An algorithm for the Push operation: push (int item) inserts the element to
the top of the stack [max size].
Step 1: Start
Step 2: Initialize
Set top= -1
Step 3: Repeat steps 3 to 5 until top < max size-1
Step 4: Read item.
Step 5: Set top = top +1
Step 6: Set stack [top] = item
Step 7: Otherwise Print “stack is over fow”
Step 8: Stop
An algorithm for the Pop operation: the pop ( ) removes the
element from the top of the stack
• Step 1: Start
• Step 2: Repeat step 3 to 5 until top >= 0
• Step 3: Set item = Stack[top]
• Step 4: Set top = top -1
• Step 5:Print, No deleted is, Item.
• Step 6: Otherwise Print stack under flows.
• Step 7: Stop
Abstract Data Type (ADT)
• A stack contains elements of the same type arranged in sequential order and
push and pop operations occur at one end at the top of the stack. The
following operations may be carried out on the stack:
• Push () – Insert an item on one end of the stack called the top.
• Pop () – Removes and returns the item to the top of the stack, if it is not
• empty.
• Top () – Returns the element to the top of the stack without deleting it,
• if the stack is not empty.
• Size () – Returns the number of items within the stack.
• IsEmpty () – Returns true if it is empty, otherwise returns false.
• IsFull () – Returns true if the stack is full or returns false.
Example of ADT
The Stack Abstract Data Type
• Stacks are the simplest of all data structures, yet they are also among the
most important. They are used in a host of different applications, and as a
tool for many more sophisticated data structures and algorithms. Formally,
a stack is an abstract data type (ADT) such that an instance S supports the
following two methods:
• S.push(e): Add element e to the top of stack S.
• S.pop( ): Remove and return the top element from the stack S; an error
occurs if the stack is empty
• Additionally, let us define the following accessor methods for convenience:
• S.top( ): Return a reference to the top element of stack S, without removing
it; an error occurs if the stack is empty.
• S.is empty( ): Return True if stack S does not contain any elements.
• len(S): Return the number of elements in stack S; in Python, we
implement this with the special method len()… .
• By convention, we assume that a newly created stack is empty, and that
there is no a priori bound on the capacity of the stack. Elements added to
the stack can have arbitrary type
#include <stdio.h> break; }
int stack[10],i,j,choice=0,n,top=-1; case 2: pop();
void push(); break; void pop ()
void pop(); case 3: show(); {
void show(); break; if(top == -1)
void main () case 4: printf("Exiting...."); {
{ break; printf("Underflow");
printf("Enter the number of elements default: printf("Please Enter valid }
in the stack "); choice "); else
scanf("%d",&n); } top = top -1;
printf("*********Stack operations using } }
array*********"); } void show()
printf("\ void push () {
n----------------------------------------------\n"); { for (i=top;i>=0;i--)
while(1) int val; {
{ if (top == n ) printf("%d\n",stack[i]);
printf("Chose one from the below { }
options...\n"); printf("\n Overflow"); if(top == -1)
printf("\n1.Push\n2.Pop\n3.Show\ } {
n4.Exit"); else printf("Stack is empty");
printf("\n Enter your choice \n"); { }
printf("Enter the value?"); }
scanf("%d",&choice); scanf("%d",&val);
switch(choice) top = top +1;
{ stack[top] = val;
case 1: push(); }
Queue:
Defining Queue ADT
• A list with the restriction that insertion can be performed at one end (tail or rear) and
deletion can be performed at other end (front or head).
• FIFO
Operations
1. Enqueue (x) or Push(x) or Insert (x)
2. Dequeue () or Pop() or Remove ()
3. Front ()
4. IsEmpty()
5. IsFull()
All these operations can be performed in constant time or O(1)
Applications of Queue
• Printer shared in a network
• Process scheduling in a processor
• Wait scenario simulation
Queue implementation using Array
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void insert()
{
int add_item;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
{
/*If queue is initially empty */
front = 0;
rear=0;
}
else
{
rear = rear + 1;
}
queue_array[rear] = add_item;
}
} /* End of insert() */
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /* End of display() */
Stack using Linked List Representation
• Stack Data Structure As we already know, stacks are linear data structures. This
means that their contexts are stored in what looks like a line. An array, too, is a sort
of linear data structure in which you can access any element directly. However, in a
stack, you can only access the element at its top.
• Stack Implementation with Linked Lists
One disadvantage of using an array to implement a stack is the wasted space---
most of the time most of the array is unused. A more elegant and economical
implementation of a stack uses a linked list, which is a data structure that links
together individual data objects as if they were ``links'' in a ``chain'' of data.
• Top of the stack at the tail
Imagine the scenario where the top of the stack is at the end of the linked
list. Since the Stack ADT uses a LIFO manner to retrieve data, in this case,
new objects would have to be added to the end of the linked list, and
retrieved from the end of the linked list too.
Continued…..
• Create a node first and allocate memory to it.
• If the list is empty then the item is to be pushed as the start node of the list.
This includes assigning value to the data part of the node and assign null to
the address part of the node.
• If there are some nodes in the list already, then we have to add the new
element in the beginning of the list (to not violate the property of the stack).
For this purpose, assign the address of the starting element to the address
field of the new node and make the new node, the starting node of the list.
• Time Complexity : o(1)
Continued…..
void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed");
}
}
Deleting a node from the stack (POP operation)
Deleting a node from the top of stack is referred to as pop operation. Deleting a
node from the linked list implementation of stack is different from that in the
array implementation. In order to pop an element from the stack, we need to
follow the following steps :
1) Check for the underflow condition: The underflow condition occurs when we
try to pop from an already empty stack. The stack will be empty if the head
pointer of the list points to null.
2) Adjust the head pointer accordingly: In stack, the elements are popped only
from one end, therefore, the value stored in the head pointer must be deleted
and the node must be freed. The next node of the head node now becomes the
head node.
Time Complexity : o(n)
INT POP()
{
ST *TEMP;
INT NO;
TEMP = TOP;
IF(TOP == NULL)
{
PRINTF("STACK IS ALREADY EMPTY");
EXIT(0);
}
ELSE
{
NO = TEMP->NO;
TOP = TOP -> NEXT;
FREE(TEMP);
}
RETURN(NO);
}
Queue using Linked list
• The array implementation can not be used for the large scale applications where
the queues are implemented. One of the alternative of array implementation is
linked list implementation of queue.
• The storage requirement of linked representation of a queue with n elements is
o(n) while the time requirement for operations is o(1).
• In a linked queue, each node of the queue consists of two parts i.e. data part and
the link part. Each element of the queue points to its immediate next element in the
memory.
• In the linked queue, there are two pointers maintained in the memory i.e. front
pointer and rear pointer. The front pointer contains the address of the starting
element of the queue while the rear pointer contains the address of the last element
of the queue.
• Insertion and deletions are performed at rear and front end respectively. If front
and rear both are NULL, it indicates that the queue is empty.
Continued……
The linked representation of queue is shown in the following figure.
The insert operation append the queue by adding an element to the end of the queue. The new element will be
the last element of the queue.
Firstly, allocate the memory for the new node ptr by using the following statement.
• However, if elements with the same priority occur, they are served according to their order in
the queue.
• Generally, the value of the element itself is considered for assigning the priority. For example,
• The element with the highest value is considered the highest priority element. However, in
other cases, we can assume the element with the lowest value as the highest priority
element.
Min Priority Queue: In min priority Queue minimum number of value gets the highest priority and lowest
number of element gets the highest priority.
Max Priority Queue: Max priority Queue is the opposite of min priority Queue in it maximum number
value gets the highest priority and minimum number of value gets the minimum priority.
Print()
FOR(i=Front;i<=Rear;i++)
PRINT(Q[i],Pr[i])