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

Module - II

The document discusses one-dimensional and two-dimensional arrays, including how to declare and access elements in arrays. It also covers stacks and queues, defining them as data structures that follow LIFO and FIFO principles respectively, and describes common stack and queue operations like push, pop, enqueue, and dequeue. Evaluation of arithmetic expressions using stacks is presented as an example application.

Uploaded by

angel0724
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Module - II

The document discusses one-dimensional and two-dimensional arrays, including how to declare and access elements in arrays. It also covers stacks and queues, defining them as data structures that follow LIFO and FIFO principles respectively, and describes common stack and queue operations like push, pop, enqueue, and dequeue. Evaluation of arithmetic expressions using stacks is presented as an example application.

Uploaded by

angel0724
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT - II

One-Dimensional Arrays
• A list of values with the same data type that are stored using a
single group name (array name).
• General array declaration statement:
data-type array-name[number-of-items];

• The number-of-items must be specified before declaring the


array.
int SIZE = 100;
float arr[SIZE];

• Individual elements of the array can be accessed by specifying


the name of the array and the element's index:
arr[3]
One-Dimensional Arrays (cont.)
The array name arr identifies the
starting location of the array

arr[0] arr[1] arr[2] arr[3] arr[4]


Two-dimensional Arrays
• A two-dimensional array consists of both rows and columns of
elements.
• General array declaration statement:
data-type array-name[number-of-rows][number-of-columns];

• The number-of-rows and number-of-columns must be specified before


declaring the array.
const int ROWS = 100;

const int COLS = 50;

float arr2D[ROWS][COLS];
What is a stack?
• It is an ordered group of homogeneous items of
elements.
• Elements are added to and removed from the top of the
stack (the most recently added items are at the top of
the stack).
• The last element to be added is the first to be removed
(LIFO: Last In, First Out).
Stack Specification
• Definitions: (provided by the user)
– MAX_ITEMS: Max number of items that might be on the stack

– ItemType: Data type of the items on the stack

• Operations
– MakeEmpty

– Boolean IsEmpty

– Boolean IsFull

– Push (ItemType newItem)

– Pop (ItemType& item)


Push
• Function: Adds new Item to the top of the stack.
• Preconditions: Stack has been initialized and is not full.
• Postconditions: new Item is at the top of the stack.

Algorithm:
Step-1: If TOP = Max-1

Print “Overflow”

Goto Step 4

Step-2: Set TOP= TOP + 1

Step-3: Set Stack[TOP]= ELEMENT

Step-4: END
Pop
• Function: Removes top Item from stack and returns it in
item.
• Preconditions: Stack has been initialized and is not empty.
• Postconditions: Top element has been removed from stack.
• Algorithm:
Step-1: If TOP= NULL

Print “Underflow”

Goto Step 4

Step-2: Set VAL= Stack[TOP]

Step-3: Set TOP= TOP-1


Step-4: END
Stack overflow

• The condition resulting from trying to push an element onto a full

stack.

if(!stack.IsFull())

stack.Push(item);

Stack underflow

• The condition resulting from trying to pop an empty stack.

if (!stack.IsEmpty())

stack.Pop(item);
Applications of Stack
• Evaluation of Arithmetic Expressions

• Backtracking

• Delimiter Checking

• Reverse a Data

• Processing Function Calls


Evaluation of Arithmetic Expressions
Evaluation of Arithmetic Expression requires two steps:
• First, convert the given expression into special notation.

• Evaluate the expression in this new notation.

Notations for Arithmetic Expression


• There are three notations to represent an arithmetic expression:
– Infix Notation

– Prefix Notation

– Postfix Notation
Evaluation of Arithmetic Expressions
Infix Notation

The infix notation is a convenient way of writing an expression in which each


operator is placed between the operands.

Example: A + B, (C - D) etc.
Prefix Notation
The prefix notation places the operator before the operands. This notation
was introduced by the Polish mathematician and hence often referred to as polish
notation.

Example: + A B, -CD etc.


Postfix Notation

The postfix notation places the operator after the operands. This notation is
just the reverse of Polish notation and also known as Reverse Polish notation.
Example: AB +, CD+, etc.
Conversion of Arithmetic
Expression into various Notations
Infix Notation Prefix Notation Postfix Notation
A*B *AB AB*
(A+B)/C /+ ABC AB+C/
(A*B) + (D-C) +*AB - DC AB*DC-+

Operator Priority

Operators Associativity

^ exponentiation Right to left


*Multiplication, /division Left to right
+ addition, - subtraction Left to right
Conversion of Arithmetic
Expression into Postfix Notations
Conversion Rules:

1. No two operator with same priority stayed in stack

2. Highest priority can’t be placed before lowest priority.

3. Always pop the operator inside the ( );

Example : A+B * (C+D)/F+D*E

Postfix ABCD+*F/+DE*+
Postfix Notations Evaluation
using Stack
Conversion Rules:

1. Empty the stack

2. Read the single character a time

3. If it’s a number push into stack

4. If it’s a operator pop last two elements and operate using the operator and
push the result into the stack.

Input: 6 5 2 3 + 8 * + 3 -

Result : 39
Tower of Hanoi
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs)
and more than one rings is as depicted

These rings are of different sizes and stacked upon in an ascending order, i.e.
the smaller one sits over the larger one. There are other variations of the puzzle
where the number of disks increase, but the tower count remains the same.
Tower of Hanoi
Rules:

The mission is to move all the disks to some another tower without
violating the sequence of arrangement.
o Only one disk can be moved among the towers at any given time.
o Only the "top" disk can be removed.
o No large disk can sit over a small disk.

Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This
presentation shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps
Tower of Hanoi Algorithm
Algorithm:
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to destination
Step 3 − Move n-1 disks from aux to destination

START
Procedure Hanoi(disk, source, dest, aux)

IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF

END Procedure
Array based Stacks
o It forms the stack for Stack implementation using arrays.

o All the stack operations can be done.


Push Operation
 Increment the top variable of the stack so that it can refer to the next memory
location.
 Add a data element at the increment top position.

If top = n

stack is full

Else

top = top + 1

stack(top) = data

end
Pop Operation
 The value of the top variable will be incremented by one whenever you delete an item
from the stack
Begin

if top = 0

stack is empty

else

value = stack(top)

top= =top -1

end
Linked Stacks
• The main advantage of using a linked list over arrays is that it is possible to
implement a stack that can shrink or grow as much as needed.
• Using an array will put a restriction on the maximum capacity of the array which
can lead to stack overflow. Here each new node will be dynamically allocated. so
overflow is not possible.

Stack Operations:
• push(): Insert a new element into the stack i.e just insert a new element at the
beginning of the linked list.
• pop(): Return the top element of the Stack i.e simply delete the first element
from the linked list.
• peek(): Return the top element.
• display(): Print all elements in Stack
Linked Stacks
• Need to follow a simple rule in the implementation of a stack which is last in
first out and all the operations can be performed with the help of a top variable.
Let us learn how to perform Pop, Push, Peek, and Display operations

4900
Linked Stacks
Recursion using Stacks
Recursion using Stacks
Queue
• It is an ordered group of homogeneous items of
elements.
• Queues have two ends:
– Elements are added at one end.
– Elements are removed from the other end.
• The element added first is also removed first
(FIFO: First In, First Out).
Queue Specification
• Definitions: (provided by the user)
– MAX_ITEMS: Max number of items that might be on the queue

– ItemType: Data type of the items on the queue

• Operations
– MakeEmpty

– BooleanA IsEmpty

– Boolean IsFull

– Enqueue (ItemType newItem)

– Dequeue (ItemType& item)


Enqueue
• Function: Adds newItem to the rear of the queue.

• Preconditions: Queue has been initialized and is not full.

• Postconditions: newItem is at rear of queue.

Algorithm
o START

o Check if the queue is full.

o If the queue is full, produce overflow error and exit.

o If the queue is not full, increment rear pointer to point the next empty

space.
o Add data element to the queue location, where the rear is pointing.

o return success.
Dequeue
• Function: Removes front item from queue and returns it in item.

• Preconditions: Queue has been initialized and is not empty.

• Postconditions: Front element has been removed from queue.

• Algorithm
o START

o Check if the queue is empty.

o If the queue is empty, produce underflow error and exit.

o If the queue is not empty, access the data where front is pointing.

o Increment front pointer to point to the next available data element.

o Return success.

o END
Queue overflow
• The condition resulting from trying to add an element onto a full
queue.
if(!q.IsFull())
q.Enqueue(item);

Algorithm for IsFull


o START
o If the count of queue elements equals the queue size, return true
o Otherwise, return false
o END
Queue underflow
• The condition resulting from trying to remove an element
from an empty queue.

if(!q.IsEmpty())
q.Dequeue(item);

Algorithm for IsEmpty


o START

o If the count of queue elements equals zero, return true

o Otherwise, return false

o END
Example
Example
Example
Example
Array Based Queue
• The queue is a linear collection of distinct entities like
an array.
• Queue possesses some restrictions while performing
insertion and deletion.
• In the case of a queue, it can perform both insertion and
deletion only at specific ends, i.e., rear and front nodes.
• Whereas arrays do not follow any order for these
operations.
Array Based Queue

• The array shown in the diagram below consists of 11 characters


having S at the front and N at the rear node.
Array Based Queue

• The value of the rear pointer becomes 11, whereas the front
pointer remains the same
Array Based Queue

• After deleting an element from the queue, the value of the front
pointer will change from 0 to 1.
Drawbacks of Array based Queue
• Memory Wastage

• The size of the queue is 10, and the front pointer has already reached location 5, thus
wasting newly created empty spaces.

• Deciding the array size


• User can extend the queue at the runtime depending upon the problem.
• It is almost impossible to extend an array size at runtime.
Linked Queue
• In a linked queue, each node of the queue consists of
two fields, i.e., data field and reference field.
• Each entity of the linked queue points to its immediate
next entity in the memory.
• Two pointers are preserved in the memory to keep
track of the front and rear node.
• The first pointer stores the location where the queue
starts, and another pointer keeps track of the last data
element of a queue.
Linked Queue

• The diagram consists of a linked list representation of queue


comprising 3 data fields and addresses of the subsequent entities
in a queue.
Linked Queue
• Enqueue() Operation

• insert a new node located at address 350 and consisting 7 in its data
field. For that to happen, just update the value of the rear pointer and
address field of the previous node.
Linked Queue
• Dequeue() Operation

• After deleting an element from the linked queue, the value of the
front pointer will change from 100 to 200.
Double Ended Queue
• A double-ended queue is an abstract data type similar to an simple
queue.
• It allows you to insert and delete from both sides means items can
be added or deleted from the front or rear end.
Insertion at rear end
Step -1: [Check for overflow]
if(rear==MAX)
Print("Queue is Overflow”);
return;
Step-2: [Insert element]
else
rear=rear+1;
q[rear]=no;
[Set rear and front pointer]
if rear=0
rear=1;
if front=0
front=1;

Step-3: return
Insertion at front end
Step-1 : [Check for the front position]
if(front<=0)
Print (“Cannot add item at front end”);
return;

Step-2 : [Insert at front]


else
front=front-1;
q[front]=no;
Step-3 : Return
Deletion at front end
Step-1 [ Check for front pointer]
if front=0
print(" Queue is Underflow”);
return;
Step-2 [Perform deletion]
else
no=q[front];
print(“Deleted element is”, no);
[Set front and rear pointer]
if front=rear
front=0;
rear=0;
else
front=front+1;
Step-3 : Return
Deletion at rear end
Step-1 : [Check for the rear pointer]
if rear=0
print(“Cannot delete value at rear end”);
return;
Step-2: [ perform deletion]
else
no=q[rear];
[Check for the front and rear pointer]
if front= rear
front=0;
rear=0;
else
rear=rear-1;
print(“Deleted element is”,no);

Step-3 : Return
Circular Queue
• A circular queue also known as Ring Buffer is an
extended version of a linear queue.

• It follows the First In First Out principle with the


exception that it connects the last node of a queue to its
first by forming a circular link.
Circular Queue

• Front - Used to get the starting element of the Circular Queue.


• Rear - Used to get the end element of the Circular Queue.
• enQueue(value) - Used to insert a new value in the Circular Queue.
This operation takes place from the end of the Queue.
• deQueue() - Used to delete a value from the Circular Queue. This
operation takes place from the front of the Queue.
Insertion in Circular Queue
Deletion in Circular Queue

You might also like