You are on page 1of 53

Data Structures and Algorithms

Lecture 02

Manish Aryal
Data Structures and Algorithms
Key Learning Points
 Course Introduction: Evaluation Scheme, Objectives,
Texts & References
 Review of Computer Programming
 Concepts of Data Structures
 Data Structure
▪ The logical or mathematical model of particular organization of
data is called as a Data Structure
▪ Array, Structure, List/Linked List, graph, e.t.c.
 Algorithm
▪ Step-by-step procedure used to solve a problem using a
machine which should stop and produce result at some point of2
Data Structures and Algorithms
Teach to Learn
 Two dimensional arrays are also called

a. tables b. matrix c. both of above d. none of above

 A variable P is called pointer if

a. P contains the address of an element in DATA.

b. P points to the address of first element in DATA


c. P can store only memory addresses
d. P contain the DATA and the address of DATA

 Which of the following data structure can store the non-homogeneous data elements?
a. Arrays b. Records c. Pointers d. None

 When new data are to be inserted into a data structure, but there is no available space;

this situation is usually called


a. underflow b. overflow c. housefull d. saturated
3
Data Structures and Algorithms
Teach to Learn {Contd..}
 Pseudocode is the combination of ……………… and ………………..

 ……………. or ……………. Model of organizing data is called as …….. ………..

 ……… and ……… are used to represent data organized in a data structure.

 …………, ……….., ………….. and ………….. Are four major operations that can be

performed in data structure


 Accessing each record exactly once to process certain data in data structure is

called as …………….
 Algorithm can be defined as …………. to a …………..

 Algorithms must eventually ………. and produce ……….


4
Stacks and Queues
Contents

 Stack Operations
 Stack Application: Evaluation of Infix, Postfix
and Prefix Expressions
 Operations in Queue, Enqueue and Dequeue
 Linear and Circular Queue
 Priority Queue

5
Stacks and Queues
Objectives
 After completing this chapter you will be able to:
 Define an Abstract Data Type (ADT)
 Define Stack as an ADT
 Implement stack
 Explain different operations that can be applied to stack
 Evaluate arithmetic expressions represented as Polish Notation
 Define Queue as an ADT
 Implement Queue
 Explain different operations that can be applied to queue
 Explain different types of Queue
 Attempt 10 marks’ in final exams 6
Stacks and Queues
Before starting
 Abstract Data Type (ADT)
 an abstract data type (ADT) s defined as a
mathematical model of the data objects that make up a
data type as well as the functions that operate on these
objects
 there are no standard conventions for defining them
 Examples:
▪ array
▪ stack: "push”, "pop", “isempty”, e.t.c
▪ queue: “enqueue", "dequeue“, e.t.c 7
Stacks
Definition
 A Stack is list of elements in which an element may be
inserted or deleted only at one end, called the top of the
stack
 This means that elements are removed from stack in the
reverse order of that in which they were inserted in to the
stack
 So Stack is a LIFO (last in, first out) data structure
 Examples:
 plates in a cafeteria
 return addresses for function calls
 Implementation:
 static: fixed size, implemented as array
 dynamic: variable size, implemented as linked list 8
Stacks
Operations And Functions
 Operations:
 push: add a value onto the top of the stack
 pop: remove a value from the top of the stack
 Functions:
 isFull: true if the stack is currently full, i.e., has
no more space to hold additional elements
 isEmpty: true if the stack currently contains no
elements

9
Stacks
Operations - Example
 A stack that can hold char values:

G
K K
push('E'); push('K'); push('G');
E E E

10
Stacks
Operations - Example
 A stack that can hold char values:

K
pop(); pop(); pop();
(remove G) E (remove K) E (remove E)

11
Stacks
Implementation
 Procerure for push(item)

1.If (top>MAXSIZE)
1.Print “stack overflow”
2.end
2.top++
3.stack[top]==item
4.return
12
Stacks
Implementation {Contd..}
 Procerure for pop(item)

1.If (top=0)
1.Print “stack underflow”
2.return
2.Item==stack[top]
3.top--
4.return 13
Stacks
Implementation in C
//Program for Stack implementation through Array
#include <stdio.h>
#include<ctype.h>
# define MAXSIZE 200
int stack[MAXSIZE];
int top;//index pointing to the top of stack
void main()
{
void push(int);
int pop();
int will=1,i,num;
clrscr(); 14
Stacks
Implementation in C{Contd..}
while(will ==1)
{
printf("MAIN MENU:\n\t1.Add element to stack\n\t2.Delete element from
the stack");
scanf("%d",&will);
switch(will)
{
case 1:
printf("Enter the data... ");
scanf("%d",&num);
push(num);
break; 15
Stacks
Implementation in C{Contd..}
case 2:
i=pop();
printf("\n\nValue returned from pop function is %d ",i);
break;
default: printf("\n\nInvalid Choice. ");
}
printf("\nDo you want to do more operations ( 1 for yes, any other key to exit) ");
scanf("%d" , &will);
} //end of outer while
} //end of main

16
Stacks
Implementation in C{Contd..}
void push(int y) // inserting data into stack
{
if(top>MAXSIZE)
{
printf("\n\n\n\nSTACK FULL");
return;
}
else
{
top++;
stack[top]=y;
}
} // end of push() 17
Stacks
Implementation in C{Contd..}
int pop() // deleting data from stack
{
int a;
if(top<=0)
{
printf("\n\n\n\nSTACK EMPTY");
return 0;
}
else
{
a=stack[top];
top--;
}
return(a);
} // end of push() 18
Stacks
Application: Evaluation of Expressions

 In normal way of writing, an operator is embedded


between two operands (in case of binary operators)
 This form of expression is called as Infix Form
 Polish mathematician Jan Lukasiewicz discovered a
unique way of representing mathematical expressions
 In his honour, this method has been named as Polish
Notation

19
Stacks
Application: Evaluation of Expressions {Contd..}

 There are two forms of Polish Notation


 Postfix Form
 Prefix Form

 Examples

Infix Form Postfix Form Prefix Form


X+Y XY+ +XY
X-Y+Z XY-Z+ +-XYZ
X+Y*Z XYZ*+ +X*YZ
(W-X)*(Y+Z) WX-YZ+* *-WX+YZ

20
Stacks
Application: Evaluation of Expressions {Contd..}
 Evaluating expressions in Postfix Form

1. Start with an empty stack S of type of operand


2. While(not end of input)
1. SYMBOL=next input
2. If (SYMBOL is an operand)
1. push(SYMBOL)
3. else
1. right_op= pop(S[top])
2. left_op=pop(S[top])
3. push(left_op ℗ right_op)

3. result=pop(S[top])
4. exit 21
Stacks
Application: Evaluation of Expressions {Contd..}
 Evaluating expressions in Postfix Form

Infix Postfix
15+17*9-21/7 15 17 9 *+21 7 / -
Input Left Operand Right Operand Result Stack
(SYMBOL) (left_op) (right_op) (left_op SYMBOL right_op) (S)
15 15
17 15 17
9 15 17 9
* 17 9 153 15 153
+ 15 153 168 168
21 15 153 168 168 21
7 15 153 168 168 21 7
/ 21 7 3 168 3
- 168 3 165 165
22
Stacks
Application: Evaluation of Expressions {Contd..}
 Evaluating expressions in Prefix Form

1. Start with an empty stack S of type of operand


2. While(not end of input)
1. SYMBOL=next input
2. If (SYMBOL is an operand)
1. push(SYMBOL)
3. Else
1. left_op=pop(S[top])
2. right_op=pop(S[top])
3. push(left_op SYMBOL right_op)

3. result=pop(S[top])
4. Exit 23
Stacks
Application: Evaluation of Expressions {Contd..}
 Evaluating expressions in Prefix Form

Infix Prefix
15+17*9-21/7 + 15- * 17 9 / 21 7
Input Left Operand Right Operand Result Stack
(SYMBOL) (left_op) (right_op) (left_op SYMBOL right_op) (S)
7 7
21 7 21
/ 21 7 3 3
9 21 7 3 39
17 21 7 3 3 9 17
* 17 9 153 3 153
- 153 3 150 150
15 153 3 150 150 15
+ 15 150 165 165
Prefix expression is evaluated from right to left 24
Stacks
Application: Infix to Postfix Conversion
 Suppose I is an arithmetic expression in Infix Form and converts it to Postfix expression P
1. Push “(“ onto STACK and add “)” to the end of I
2. Scan I from left to right until STACK is empty
1. If an operand is encountered, add it to P
2. If a left parenthesis is encountered, push it to STACK
3. If an operator ℗ is found, then
1. Repeatedly pop each operator which has the same precedence as or higher than ℗ from STACK and add
to P
2. Add ℗ to STACK
4. If a right parenthesis is encountered, then
1. Repeatedly pop from STACK and add to P each operator until a left parenthesis is encountered
2. Remove the left parenthesis and do not add it to P

3. Exit

25
Stacks
Application: Infix to Prefix Conversion
STEP 1 : Read the given infix expression into string called I which converts to Prefix expression P.
STEP 2 : Reverse the infix string and read one character at a time and perform the following
operations :
If the read character is an operand, then add the operand to the P.
     If the read character is not an operand, then check
        If the stack is not empty and precedence of the top of the stack operator is higher than
the read operator,
       then pop the operator from stack and add this operator to the P.
       Else push the operator onto the stack.
STEP 3 :    Repeat STEP 2 till all characters are processed from the input string.
STEP 4 :    If stack is not empty, then pop the operator from stack and add this operator to the
prefix string.
STEP 5 :    Repeat STEP 4 till all the operators are popped from the stack.
STEP 6 :    Reverse the prefix string and display the result of the given infix expression or the
resultant prefix expression stored in a string called prefix from this algorithm.
Step 7: Exit
26
Data Structures and Algorithms

Lecture 03

Manish Aryal
Stacks
Key Learning Points
 Stack:
 A list in which we can add or remove data from only one end called as a Top
 LIFO
 Operations:
 PUSH: add data from Top
 POP: remove data from Top
 Application:
 Evaluation of expressions in Polish Notation
 Infix Form: 15+17*9-21/7
 Postfix Form: 15 17 9 *+21 7 / -
 Prefix Form: + 15- * 17 9 / 21 7
28
Stacks
Teach to Learn
 Stack pointer points to the topmost element of the stack. [True/False]
 Stack is a LIFO list. [True/False]
 Postfix equivalent of a+b*c is
a. a b c * + b. a b c + * c. a b + c * d. a * b c+
 Value of prefix expression +2*48 is
a. 14 b. 16 c. 20 d. 34
 Prefix expressions are represented using …….. notation.
 Stack doesn’t have any data and you try to remove data. This condition
is called as stack ……………..
 Condition opposite to underflow is ……………..
29
Queues
Definition
 A queue is an ordered list in which all insertion take place
one end, called the rear and all deletions take place at the
opposite end, called the front
 If we insert the elements A, B, C, D, in that order, then A
is the first element we delete from the queue
 A stack is also known as a First-In-First-Out (FIFO) list
 Example:
 Line at a petrol pump
 Implementation:
 Static Implementation: Using an array
 Dynamic Implementation: Using linked list 30
Queues
Operations and Functions
 Operations:
 Insert: Adding data at the Rear of a Queue. Also known as Enqueue
 Delete: Removing data from the Front of a Queue. Also known as Dequeue
 * Deque: is also used to represent double-ended queue in which
wee can add or remove data at both ends but not at the middle
 Functions
 isFull: true if the queue is currently full, i.e., has no more space to
hold additional elements
 isEmpty: true if the queue currently contains no elements

31
Queues
Operations: Example

32
Queues
Implementation

// implementation of queue structure


# define MAX_SIZE
struct queue
{
int items[MAX_SIZE];
int front, rear;
};
struct queue q;

33
Queues
Implementation {Contd..}
// implementation of add()
void add(struct queue pq, int x)
{
// Check for overflow
if(pq.rear==MAX_SIZE-1)
{
printf(“Queue Overflow”);
exit();
}
pq.items[pq.rear]=x;
pq.rear++;
return;
}

34
Queues
Implementation {Contd..}
// implementation of delete()
void add(struct queue pq, int x)
{
// check for under flow
if(pq.rear==pq.front)
{
printf(“Queue Under”);
exit();
}
x=pq.items[pq.front]=x;
pq.front++;
return;
}

35
Queues
Implementation {Contd..}
// implementation of isempty()
void isempty(struct queue pq)
{
if(pq.rear==pq.front)
return (TRUE);
else
return(FALSE)
}

// implementation of isfull()
void isfull(struct queue pq)
{
if(pq.rear==MAX_SIZE-1)
return (TRUE);
else
return(FALSE)
}
36
Queues
Implementation {Contd..}
// Program for Queue implementation through Array

#include <stdio.h>
#include<ctype.h>
# define MAXSIZE 200

int q[MAXSIZE];
int front=0, rear=0;
void add(int);
int del();

void main()
{

int will=1,i,num;
clrscr();
printf("Program for queue demonstration through array"); 37
Queues
Implementation {Contd..}

while(will ==1)
{
printf("\n\nMAIN MENU:\n1.Add element to queue\n2.Delete

element from the queue\n");


scanf("%d",&will);

switch(will)
{
case 1:
printf("\nEnter the data... ");
scanf(" %d",&num);
add(num);
break;

38
Queues
Implementation {Contd..}

case 2: i=del();
printf("\nValue returned from delete function is %d ",i);
break;

default: printf("\nInvalid Choice ... ");


}

printf("\nDo you want to do more operations on Queue ( 1 for yes, any other
key to exit)?\n");
scanf("%d" , &will);
} //end of outer while
}

39
Queues
Implementation {Contd..}

void add(int a)
{

if(rear>MAXSIZE)
{
printf("\n\n\tQUEUE FULL");
return;
}
else
{
q[rear]=a;
rear++;
// printf("\n\nValue of rear = %d and the value of

front is %d",rear,front);
}
} 40
Queues
Implementation {Contd..}

int del()
{
int a;
if(front == rear)
{
printf("\n\n\tQUEUE EMPTY");
return(0);
}
else
{
a=q[front];
front++;
}
return(a);
}

41
Queues
Circular Queue
 What are the limitations of linear queue?
Queues
Circular Queue
 In Circular queue, the rear may increase even after it has
reached MAXSIXE-1
 However this increment makes its value 0
 Similarly, front is allowed to increment when the deletion
has occurred
 It is possible that value of rear may be less than front but
deletion is always done at front and insertions from rear

 How do you know the number of elements in the queue?


Queues
Circular Queue
 Total number of elements in queue can be evaluated by:
(rear-front)+1 if rear>=front
 If at any time rear<front, at least one deletion has occurred
and total number of insertion so far has been more than
MAXSIZE and total number of elements can be evaluated
by:
MAXSIZE-front-rear+1
 In normal situation when front < rear, number of elements is
evaluated by:
rear-front+1
Queues
Circular Queue
EMPTY QUEUE

[1] [2] [1] [2]


J2 J3
[0] [3] [0] J1 [3]

[5] [4] [5] [4]

front = 0 front = 0
rear = 0 rear = 3
Queues
Circular Queue
FULL QUEUE FULL QUEUE

[1] [2] [1] [2]


J2 J3 J8 J9

[0] J1 J4 [3] [0] J7 J4 [3]


J6 J5 J6 J5
[5] [4] [5] [4]

front =0 front =3
rear = 5 rear = 2
Queues
Circular Queue: Add Element

void addq(int front, int rear, element item)


{
/* add an item to the queue */
rear = (rear +1) % MAX_QUEUE_SIZE;
if (front == rear) /* reset rear and print error */
{
printf(“\n Queue Overflow!”);
exit();
}
queue[rear] = item;
}
47
Queues
Circular Queue
element deleteq(int front, int rear)
{
element item;
/* remove front element from the queue and put it in item */
if (front == rear)
{
printf(“\nQueue Underflow!”);
exit();
} /* queue_empty returns an error key */
front = (front+1) % MAX_QUEUE_SIZE;
return (queue[front]);
}
48
Queues
Priority Queue

 A priority queue is a collection of elements such


that each element has been a priority and the
order in which elements are deleted and
processed according to following rule:
1. An element with higher priority is processed before
elements with lower priority
2. If two or more elements have same priority, they are
processed according to the order in which they were
inserted to the queue
49
Queues
Priority Queue

 There are various ways for implementing a


priority queue
 Two most commonly used ways are:
1. One-way list representation
2. Using Multiple Queue

50
Queues
Priority Queue: Using Multiple Queue

 In this approach, we maintain separate queue for


each level of priority
 Each such queue will appear in its own array and
has its own pair of pointers

51
Queues
Assignment

 Writing assignment
 Write an pseudocode to implement priority queue
using multiple queues.

 Reading assignment:
 Chapter 4.2 and 4.3 from Aaron M. Tanembaum

52
Next Lecture:
List/Linked List

http://www.c.happycodings.com/Data_Structures/index.html

Thank You.

You might also like