0% found this document useful (0 votes)
39 views

Stack and Queue

The document discusses stacks and queues. It provides an overview of stacks including common operations like push and pop. It describes how stacks can be implemented using arrays or linked lists. It also discusses the queue abstract data type and how queues differ from stacks in following a FIFO rather than LIFO model. Key queue operations like enqueue and dequeue are explained. The document concludes by covering some applications of stacks, including their use in recursion and expression conversion.

Uploaded by

Aditi Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Stack and Queue

The document discusses stacks and queues. It provides an overview of stacks including common operations like push and pop. It describes how stacks can be implemented using arrays or linked lists. It also discusses the queue abstract data type and how queues differ from stacks in following a FIFO rather than LIFO model. Key queue operations like enqueue and dequeue are explained. The document concludes by covering some applications of stacks, including their use in recursion and expression conversion.

Uploaded by

Aditi Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 53

STACK AND QUEUE

STACK OVERVIEW
 Stack
 Basic operations of stack
 Pushing, popping etc.
 Implementations of stacks using
 array
 linked list
THE STACK ADT

 A stack is a list with the restriction


 that insertions and deletions can only be performed at the top of the
list

 The other end is called bottom


 Fundamental operations:
 Push: Equivalent to an insert
 Pop: Deletes the most recently inserted element
 Top: Examines the most recently inserted element
STACK
 Stacks are less flexible
 but are more efficient and easy to implement
 Stacks are known as LIFO (Last In, First Out) lists.
 The last element inserted will be the first to be retrieved
PUSH AND POP
 Primary operations: Push and Pop
 Push
 Add an element to the top of the stack
 Pop
 Remove the element at the top of the stack

empty stack push an element push another pop

top
B
top top
A A A
top
IMPLEMENTATION OF STACKS
 Any list implementation could be used to implement a
stack
 Arrays(static: the size of stack is given initially)
 Linked lists (dynamic: never become full)

 We will explore implementations based on array and


linked list
 Let’s see how to use an array to implement a stack first
ARRAY IMPLEMENTATION
 Need to declare an array size ahead of time
 Associated with each stack is TopOfStack
 for an empty stack, set TopOfStack to -1
 Push
 (1)   Increment TopOfStack by 1.
 (2)   Set Stack[TopOfStack] = X

 Pop
 (1)   Set return value to Stack[TopOfStack]
 (2)   Decrement TopOfStack by 1

 These operations are performed in very fast constant time


ARRAY IMPLEMENTATION
int stack[Max]
int top = -1;
Void push(int)
Int pop(void)
Void Main()
{ int temp;
push(20); push(60); push(80);
temp =pop();
Printf(“%d”,temp);
}
ARRAY IMPLEMENTATION
Void push( int t)
{ int item ;
if(top>=MAX – 1)
{ Printf(“Satck is Full”);
return; }
top++;
stack[top]=t;
}
ARRAY IMPLEMENTATION
int pop()
{ int item;
if(top< 0)
{ Printf(“Stack is empty”);
return(); }
item = stack[top];
top--;
return(item);
}
LINKED LIST IMPLEMENTATION
Struct Stack_LL
{ int info;
struct Stack_LL *next;
}
typedef struct Stack_LL node;
Void push( int item)
node *pop(void)
node *top, *stack;
LINKED LIST IMPLEMENTATION
Void main()
{ node *item;
top==NULL; /* Initialize top to NULL;
push(20); push(90); push(35);
item=pop();
if(item!=NULL)
Printf(“poped item %d”,item->info);
push(80); push(72);
.
}
LINKED LIST IMPLEMENTATION
Void push( int item )
{
stack = (node *)malloc(sizeof(node));
stack->info=item;
stack->next = top; /* update next ptr with top
top=stack; /*Update the top that points to top
node
}
LINKED LIST IMPLEMENTATION
node *pop()
{ node *temp;
if(top==NULL)
{ Printf(“stack is empty”); }
temp = top;
free(top)
top=temp->next;
return(temp);
}
QUEUE OVERVIEW
 Queue
 Basic operations of queue
 Enqueuing, dequeuing etc.
 Implementation of queue
 Array
 Linked list
QUEUE
 Like a stack, a queue is also a list. However, with a queue,
insertion is done at one end, while deletion is performed at
the other end.

 Accessing the elements of queues follows a First In, First


Out (FIFO) order.
 Like customers standing in a check-out line in a store, the first
customer in is the first customer served.
THE QUEUE
 Another form of restricted list
 Insertion is done at one end, whereas deletion is performed at
the other end
 Basic operations:
 enqueue: insert an element at the rear of the list
 dequeue: delete the element at the front of the list

 First-in First-out (FIFO) list


ENQUEUE AND DEQUEUE
 Primary queue operations: Enqueue and Dequeue
 Like check-out lines in a store, a queue has a front and a rear.

 Enqueue
 Insert an element at the rear of the queue
 Dequeue
 Remove an element from the front of the queue

Remove Insert
(Dequeue) front rear (Enqueue)
IMPLEMENTATION OF QUEUE
 Just as stacks can be implemented as arrays or linked
lists, so with queues.
 Dynamic queues have the same advantages over static
queues as dynamic stacks have over static stacks
QUEUE IMPLEMENTATION OF ARRAY
 Naïve way
 When enqueuing, the front index is always fixed and the rear
index moves forward in the array.
 When dequeuing, the element at the front the queue is removed.
Move all the elements after it by one position. (Inefficient!!!)

rear rear rear = -1

6 9 9

front front front


Dequeue() Dequeue() Dequeue()
QUEUE IMPLEMENTATION USING
ARRAY
#define MAX 10
void qinsert(int item);
int qdelete(void)
int queue[MAX];
int front , rear;
void main()
{ front = rear = -1;
qinsert(20); qinsert(30); qinsert(50);
display();
qdelete(); qdelete();
}
QUEUE IMPLEMENTATION USING
ARRAY
void qinsert( int item)
{ if(rear == MAX -1 )
{ printf(“Queue is Full”);
return; }
rear = rear + 1;
queue[rear]= item;
if(front = = -1) front = 0;
return;
}
QUEUE IMPLEMENTATION USING
ARRAY
int qdelete(void)
{ int item;
if(front == -1)
{ printf(“queue is empty”); return; }
else if( front > rear)
{ printf(“ q is empty”); front = rear = -1; }
else
item = queue[front];
queue[front]= Null;
front = front + 1; return(item) ;}
LINKED LIST IMPLEMENTATION OF
QUEUE
Struct linked_queue
{ int info;
struct linked_queue *next;
}
typedef struct linked_queue node;
void insertq(int item)
node *deleteq(void)
node * front, *rear;
LINKED LIST IMPLEMENTATION OF
QUEUE
void Main()
{ node * item ;
front = rear = NULL;
insertq(20); insertq(90); insert(30);
display();
item = deleteq();
insertq(80); display();
item =deleteq();
}
LINKED LIST IMPLEMENTATION OF
QUEUE
Void insertq(int temp)
{ node *new;
new = ( node *)malloc(sizeof(node));
new->info= temp;
if(front == NULL)
front = rear = new; }
else
{ rear-> next = new;
rear = rear -> next;
} rear-> next = NULL;
}
LINKED LIST IMPLEMENTATION OF
QUEUE
node * deleteq()
{ node * item;
if(front == NULL)
{ printf(“Q is empty”); return(NULL);
item = front ;
free(front);
front =item-> next;
return(item);
}
APPLICATION OF STACK
 Recursion

 Expression conversions and evaluations


 What is Recursion ?

 Sometimes, the best way to solve a problem is by solving


a smaller version of the exact same problem first

 Recursion is a technique that solves a problem by


solving a smaller problem of the same type
 When you turn this into a program, you end up with functions that
call themselves (recursive functions)
 factorial function

 Recursive Implementation

int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
ou turn this into a program, you end up with functions that call
themselves
 Iterative implementation

int Factorial(int n)
{
int fact = 1;
 
for(int count = 2; count <= n; count++)
fact = fact * count;
 
return fact;
}
RECURSION VS. ITERATION
 Iteration can be used in place of recursion
 An iterative algorithm uses a looping construct
 A recursive algorithm uses a branching structure
 Recursive solutions are often less efficient, in terms of
both time and space, than iterative solutions
 Recursion can simplify the solution of a problem, often
resulting in shorter, more easily understood source code
HOW DO I WRITE A RECURSIVE
FUNCTION?
 Determine the size factor
 Determine the base case(s)
(the one for which you know the answer)
 Determine the general case(s)
(the one where the problem is expressed as a smaller version
of itself)
 Verify the algorithm
(use the "Three-Question-Method")
 Recursive calls to f get pushed onto stack
 Multiple copies of function f, each with different arguments &
local variable values, and at different lines in function

 All computer really needs to remember for each active


function call is values of arguments & local variables and
the location of the next statement to be executed when
control goes back
 “The stack" looks a little more like :
STACK FOR RECURSSION
 Recursive functions use something called “the call stack.”
When a program calls a function, that function goes on top
of the call stack.
`
EXPRESSION CONVERSION

 Infix expression:The expression of the form a op b. When


an operator is in-between every pair of operands.
 Postfix expression:The expression of the form a b op.
When an operator is followed for every pair of operands.
 Why postfix representation of the expression? 
 The compiler first scans the expression to evaluate the expression b * c, then
again scan the expression to add a to it. The result is then added to d after
another scan.
The repeated scanning makes it very in-efficient. It is better to convert the
expression to postfix(or prefix) form before evaluation.
 Algorithm 
1. Scan the infix expression from left to right. 
2. If the scanned character is an operand, output it. 
3. Else, 
      1 If the precedence of the scanned operator is greater
than the precedence of the operator in the stack(or the
stack is empty           or the stack contains a ‘(‘ ), push it. 
      2 Else, Pop all the operators from the stack which are
greater than or equal to in precedence than that of the
scanned operator. After doing that Push the scanned
operator to the stack. (If you encounter parenthesis while
popping then stop there and push the scanned operator in
the stack.) 
 . If the scanned character is an ‘(‘, push it to the stack. 
5. If the scanned character is an ‘)’, pop the stack and
and output it until a ‘(‘ is encountered, and discard both
the parenthesis. 
6. Repeat steps 2-6 until infix expression is scanned. 
7. Print the output 
8. Pop and output from the stack until it is not empty.
POSTFIX EXPRESSION EVALUATION
INFIX TO PREFIX EXPRESSION
 Step 1: Reverse the infix expression i.e A+B*C will
become C*B+A. Note while reversing each ‘(‘ will
become ‘)’ and each ‘)’ becomes ‘(‘.
 Step 2: Obtain the “nearly” postfix expression of the
modified expression i.e CB*A+.
 Step 3: Reverse the postfix expression. Hence in our
example prefix is +A*BC
APPLICATION QUEUE
 Priority Queue
A priority queue is a special type of queue in which each
element is associated with a priority and is served
according to its priority
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
CIRCULAR QUEUE
 Circular Queue is a linear data structure in which the
operations are performed based on FIFO (First In First
Out) principle and the last position is connected back to
the first position to make a circle.

 It is also called ‘Ring Buffer’.


OPERATIONS ON CIRCULAR QUEUE
 Front: Get the front item from queue.
 Rear: Get the last item from queue.

 enQueue(value) This function is used to insert an element


into the circular queue. In a circular queue, the new element is
always inserted at Rear position.
 Steps:

 Check whether queue is Full – Check ((rear == SIZE-1 &&


front == 0) || (front == rear + 1)).
 If it is full then display Queue is full. If queue is not full then,
check if (rear == SIZE – 1 && front != 0) if it is true then set
rear=0 and insert element.
 deQueue() This function is used to delete an element from
the circular queue. In a circular queue, the element is always
deleted from front position. 
 Steps:

 Check whether queue is Empty means check (front==-1).

 If it is empty then display Queue is empty. If queue is not


empty then step 3
 Check if (front==rear) if it is true then set front=rear= -1
else check if (front==size-1), if it is true then set front=0 and
return the element.
 # define MAX 10
 int cqueue_arr[MAX];

 int front = -1;

 int rear = -1;


 void insert(int item)
{ if((front == 0 && rear == MAX-1) || (front == rear+1))
{ printf("Queue Overflow n"); return; }
if(front == -1)
{ front = 0; rear = 0;
}
else
{ if(rear == MAX-1) rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;
}
void deletion()
{ if(front == -1)
{ printf("Queue Underflown"); return; }
printf("Element deleted from queue is :%dn",cqueue_arr[front]);
if(front == rear)
{ front = -1; rear=-1; }
else
{ if(front == MAX-1)
front = 0;
else
front = front+1;
}
}

You might also like