0% found this document useful (0 votes)
38 views42 pages

DS&OOPs Unit II

The document describes the key concepts and operations for common data structures including stacks, queues, linked lists, and priority queues. It provides definitions and examples for each data structure and lists some of their applications. The document also includes 25 multiple choice questions related to data structures and their implementation with answers provided.

Uploaded by

Shanmathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views42 pages

DS&OOPs Unit II

The document describes the key concepts and operations for common data structures including stacks, queues, linked lists, and priority queues. It provides definitions and examples for each data structure and lists some of their applications. The document also includes 25 multiple choice questions related to data structures and their implementation with answers provided.

Uploaded by

Shanmathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGY

KALITHEERTHALKUPPAM, PUDUCHERRY - 605 107


Department of Electronics and Communication Engineering

SUB CODE: EC T33

SUBJECT NAME: DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING

Prepared By:
N.ARIKARAN AP/CSE
UNIT II

Stacks:
 Definition
 Operations
 Applications of stack.

Queues:
 Definition
 Operations
 Priority queues
 De queues
 Applications of queue.

Linked List:
 Singly Linked List
 Doubly Linked List
 Circular Linked List
 Linked stacks
 Linked queues
 Applications of Linked List.

P a g e | 1 DS&OOPs
2 MARKS
1. What are all the Common data structures?
• Stacks
• Queues
• Lists
• Trees
• Graphs
• Tables
2. What are the two basic types of Data structures?
1. Primitive Data structure
Eg., int,char,float
2. Non Primitive Data Structure
i. Linear Data structure
Eg., Lists Stacks Queues
ii. Non linear Data structure
Eg., Trees Graphs
3. What are the four basic Operations of Data structures?
1. Traversing
2. Searching
3. Inserting
4. Deleting
4. What is a stack? (April 2012, April 2013)
A stack is an ordered collection of items where new items may be inserted or deleted
only at one end, called the top of the stack.
A stack is a data structure that keeps objects in Last- In-First-Out (LIFO)
order, Objects are added to the top of the stack
Only the top of the stack can be accessed.
5. What are the basic operations of stack?
 Push

 Pop

 Top
Push: Push is performed by inserting at the top of stack.
Pop: pop deletes the most recently inserted element.
Top: top operation examines the element at the top of the stack and returns its value.
push pop

P a g e | 2 DS&OOPs
6. Define abstract data type(ADT) and list its advantages? (April
2013) ADT is a set of operations.
An abstract data type is a data declaration packaged together with the operations that are
meaning full on the data type.
Abstract Data Type
 Declaration of data

 Declaration of operations.
Advantages:
 Easy to debug small routines than large ones.

 Easy for several people to work on a modular program simultaneously.

 A modular program places certain dependencies in only one routine, making changes

easier.


7. What are the operations of ADT?
Union, Intersection, size, complement and find are the various operations of ADT.

8. State the different ways of representing expressions?


The different ways of representing expressions are
• Infix Notation
• Prefix Notation
• Postfix Notation

9. State the rules to be followed during infix to postfix conversions? (Nov 2012)
• Fully parenthesize the expression starting from left to right. During parenthesizing,
the operators having higher precedence are first parenthesized
• Move the operators one by one to their right, such that each operator replaces
their corresponding right parenthesis
• The part of the expression, which has been converted into postfix is to be treated as
single operand

10. Write the various applications of the stack?


• Towers of Hanoi
• Reversing a string
• Balanced parenthesis
• Recursion using stack
• Evaluation of arithmetic expressions
• Infix to postfix conversion

P a g e | 3 DS&OOPs
11. Define Infix notation?
The operator symbol is placed in between its two operands. This is called infix
notation. Example: A + B , E * F
Parentheses can be used to group the operations.
Example: (A + B) * C

12. Define Prefix notation? (April 2011)


Polish notation refers to the notation in which the operator symbol is placed before its
two operands. This is called prefix notation.
Example: +AB, *EF
The fundamental property of polish notation is that the order in which the operations are
to be performed is completely determined by the positions of the operators and operands
in the expression.
Accordingly, one never needs parentheses when writing expressions in Polish notation.

13. Define Postfix notation? (April 2011)


Reverse Polish Notation refers to the analogous notation in which the operator symbol is
placed after its two operands. This is called postfix notation.
Example: AB+, EF*
Here also the parentheses are not needed to determine the order of the operations.

14. Convert the given infix to postfix and prefix?


(j*k)+(x+y)
postfix : jk* xy++
prefix : +*jk+xy

15. Define a Queue? (April 2012)


Queue is an ordered collection of elements in which insertions are restricted to one end called the rear
end and deletions are restricted to other end called the front end. Queues are also referred as First-
In-First-Out (FIFO) Lists. enqueue

dequeue Fron Rear


e.g: Ticket counter.

16. List the operations of queue? (April 2011, April


2013) Two operations
 Enqueue-inserts an element at the end of the list called the rear.

 Dequeue-delets and returns the element at the start of the list called as the front.

P a g e | 4 DS&OOPs
17. How the enqueue and dequeue operations are performed in
queue? To enqueue an element X:
increment size and rear
set queue[rear]=x
To dequeue an element
set the return value to
queue[front]. Decrement size
increment front

18. What is the difference between a queue and a stack?


Queue Stack
Queue is typically FIFO Stack is LIFO
Elements get inserted at one end of a queue and Insertion and removal operations for a stack are
retrieved from the other done at the same end.

19. What are priority queues?


A priority queue is a collection of elements such that each element has been assigned a priority.
 Insert-inserts an element at the end of the list called the rear.

 DeleteMin-Finds, returns and removes the minimum element in the priority Queue.







20. What are the types of priority queues?
 Ascending Priority Queue

 Descending Priority Queue


21. What is an ascending priority queue?
It is a collection of items into which items can be inserted arbitrarily and from which the
smallest item can be removed.

22. What is an descending priority queue?


It is a collection of items into which items can be inserted arbitrarily and from which the
largest item can be removed.

P a g e | 5 DS&OOPs
23. Give the applications of priority queues?
There are three applications of priority queues
1. External sorting.
2. Greedy algorithm implementation.
3. Discrete even simulation.
4. Operating systems.
24. How do you test for an empty queue?
To test for an empty queue, we have to check whether REAR=HEAD where REAR is a pointer
pointing to the last node in a queue and HEAD is a pointer that points to the dummy header. In the
case of array implementation of queue, the condition to be checked for an empty queue is
REAR=max-1, front=rear+1.

25. Define a Dequeue?


Dequeue is a list that combines the properties of a stack and queue. It is linear list in
which insertions and deletions are made to or from either end of the structure.

26.List the applications of Queues?


 Checking strings of a language

 Queuing theory simulation

 Input / Output buffers

 Graph searching

 Jobs sent to a printer

 Line in a ticket counter


27. Define Linked Lists? Or What is Automatic list management?
Linked list consists of a series of structures, which are not necessarily adjacent in memory.
Each structure contains the element and a pointer to a structure containing its successor. We call
this theNext Pointer. The last cell’sNext pointer points to NULL.

A1 A2 A3 A4

28. Define HEAD pointer and NULL pointer? HEAD-


It contains the address of the first node in that list.
NULL - It indicates the end of the list structure.

29. What is a node?


The data element of a linked list is called a node.

P a g e | 6 DS&OOPs
30. What does node consist of?
Node consists of two fields: data field to store the element and link field to store the address of the
next node.

31. List three examples that uses linked list?


• Polynomial ADT
• Radix sort
• Multi lists

32. State the difference between arrays and linked lists ?


Arrays Linked Lists
Size of an array is fixed Size of a list is variable
It is necessary to specify the number It is not necessary to specify the
of elements during declaration. number of elements during
declaration
Insertions and deletions are Insertions and deletions are carried
somewhat difficult out easily
It occupies less memory than a It occupies more memory
linked list for the same number of
elements

33. List the basic operations carried out in a linked list? The
basic operations carried out in a linked list include:
• Creation of a list
• Insertion of a node
• Deletion of a node
• Modification of a node
• Traversal of the list

34. List the basic operations carried out in a linked list? The
basic operations carried out in a linked list include:
• Creation of a list
• Insertion of a node
• Deletion of a node
• Modification of a node
• Traversal of the list

P a g e | 7 DS&OOPs
35. List out the different ways to implement the list?
1. Array Based Implementation
2. Linked list Implementation
i. Singly linked list
ii. Doubly linked list
iii. Cursor based linked list

36. List out the advantages of using a linked list?


• It is not necessary to specify the number of elements in a linked list
during its declaration
• Linked list can grow and shrink in size depending upon the insertion and deletion that
occurs in the list
• Insertions and deletions at any place in a list can be handled easily and efficiently
• A linked list does not waste any memory space

37. List out the disadvantages of using a linked list?


• Searching a particular element in a list is difficult and time consuming
• A linked list will use more storage space than an array to store the same number
of elements

38. State the different types of linked lists?


The different types of linked list include
i. Singly linked list
ii. Doubly linked list
iii. Cursor based linked list
39. What are the advantages of Linked List over arrays?
1. In Linked List implementation Memory location need not be necessarily contiguous.
2. Insertion and deletions are easier and needs only one pointer assignment.
3. A small amount of memory is been wasted for storing a pointer, which is
been associated with each node.

40.What is a singly Linked List? (April 2013)


A singly linked list is a collection of nodes each node is a structure it consisting of an
element and a pointer to a structure containing its successor, which is called a next pointer.

The last cell’s next pointer points to NULL specified by zero.

P a g e | 8 DS&OOPs
41. What is a doubly linked lists?
Doubly linked list is a collection of nodes where each node is a structure
containing the following fields
1. Pointer to the previous node.
2. Data.
3. Pointer to the next node.

42. What is a circularly linked lists?


Circularly linked list is a collection of nodes , where each node is a structure
containing the element and a pointer to a structure containing its successor.
The pointer field of the last node points to the address of the first node. Thus the
linked list becomes circular.

43. List out the applications of a linked list?


Some of the important applications of linked lists are
 manipulation of polynomials,

 sparse matrices,

 stacks and queues.


44. Define circular linked list?

Circularly linked list is a collection of nodes , where each node is a structure containing
the element and a pointer to a structure containing its successor.
The pointer field of the last node points to the address of the first node. Thus the linked
list becomes circular.

P a g e | 9 DS&OOPs
45. Compare single and double linked list

Singly Doubly
It is a collection of nodes and each node is It is a collection of nodes and each node is
having one data field and next link field having one data field one previous link field
and one next link field
The elements can be accessed using next link The elements can be accessed using both
previous link as well as next link
No extra field is required hence, Node takes One field is required to store previous Link
less memory in SLL. Hence, node takes memory in DLL.
Less efficient access to elements More efficient access to elements.

46. Advantages of linked list over array?


 In Linked List implementation Memory location need not be necessarily contiguous.

 Insertion and deletions are easier and needs only one pointer assignment.

 A small amount of memory is been wasted for storing a pointer, which is been associated with
each node.

 Linked list can grow and shrink in size depending upon the insertion and deletion that occurs
in the list

 Insertions and deletions at any place in a list can be handled easily and efficiently


47. List out the applications of a linked list?
Some of the important applications of linked lists are
 manipulation of polynomials,

 sparse matrices,

 stacks and queues.

P a g e | 10 DS&OOPs
11 MARKS

LINKED LIST

If the memory is allocated before the execution of a program it is fixed and it cannot be changed.

To adopt an alternative strategy to allocated memory only when it is required. There is a special
data structure called linked list that provides a more flexible storage system and it does not required
the use of arrays.

For stack and queues, we employed arrays to represent them in computer memory. When we choose
arrays representation it is necessary to declare in advance the amount of memory to be utilized.

The memory is very important resources, so we should handle it efficiently.

Key terms;

a) Data field
b) Link field

Data field contains an actual value to be stored and processed and the link field contains the
address of the next node in the linked list.

1. Types of linked list?


1) Linear or single linked list
2) Circular linked list
3) Double linked list
4) Circular double linked list

Linear lined list or single linked list:

In the linear linked list the node is divided into two part, first part contains information field and the
second part holds the address of the next node.

Struct node

Int data;

Struct node *next;

} *start =NULL;

Start node

Data Next Data Next Data Next Data NULL

Address of the
next node

P a g e | 11 DS&OOPs
Circular linked list:

It is just like a linear or single linked list in which the next field of the last node contains the address
of the first node in the list . The nest field of the last node does not point to NULL rather it points
back to the beginning of the linked list.
Struct node
{
Int data;
Struct node *next;
} *start=NULL;

Start node

Data Next Data Next Data Next Data Next

Address of the
first node
Double linked list:

One of the most striking disadvantages of these lists is that the inability to traverse the list in
the backward.
In most of the real world applications it is necessary to reverse the list both in forward direction
and backward direction.
The most appropriate data structure for such an application is a doubly linked list.
A double linked list is one in which all nodes are linked together by multiple number of links
which help in accessing both the successor node and predecessor node form the given node
position. It provides bi-directional traversing.
Each node in a double linked list has two linked fields. These are used to point to the successor
node and predecessor nodes. Prev field holds the address of the previous node and next field holds
the address of the nest node.

Prev data next

Struct node

Int data;
Struct node *prev, *next;

} *start=NULL;

Start node

NULL data next Prev data next Prev data NULL

P a g e | 12 DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING DEPARTMENT OF ECE


Circular double linked list

In circular double linked list the node is divided into three parts, the first part contains the
address of previous node, the second part contains the information field and the third part contains
the address of the next node. But here the previous of the first node contains the address of the last
node and the next part of the last node contains the address of the first node.

Struct node

Int data;

Struct node *prev, *next;

} *start=NULL;

Start node

Next data next Prev data next Prev data next

2.Explain Linear linked list or single linked list?


In the linear linked list the node is divided into two part, first part contains information field and
the second part holds the address of the next node.

Struct node
{
Int data;
Struct node *next;
} *start =NULL;

Start node

Data Next Data Next Data Next Data NULL

Address of the
next node

P a g e | 13 DS&OOPs
Inserting an item:

Inserting a new node has three situations:


This operation is used to insert a new node in the linked list at the specified position
1. Insertion at beginning of the list
2. Insertion at middle of the list
3. Insertion at end of the list

Insertion at beginning:
- Obtain space for new node
- Assign data to the data field of the new node
- Set the next field of the new node to the beginning of the linked list
- Change the reference pointer of the linked list to point to the new node

Start

Data Next Data Next Data NULL

P X Next

Algorithm:

Node insert(node *start, int x)


{
P=(node*)malloc(sizeof(node));
p->data=x;
p->next=start;
start=p;
}
Insertion at middle:
- Obtain space for new node
- Assign data to the data field of the new node
- Set the next field of the new node to q->next
- Change the reference pointer of the linked list to point to the new node q->next=p.
q

Data Next Data Next Data NULL

P X Next

P a g e | 14 DS&OOPs
Algorithm:

q = start;

while(key != q->data && q != null)

q=q->next;

p->next = q->next;

q->next=p

Insertion at end:

Algorithm:

1. Acquire memory for new node

P=(node*)malloc(sizeof(node));

2. Assign value to the data field and make its next field NULL

p->data=X;

p->next=NULL;

3. if(start == NULL)

start=p;

4. Position a pointer q on the last node by traversing the linked list from the first node and until it
reaches the last node.

q=start;

while(q->next!=NULL)

q=q->next;

5. At last store the address of the newly acquired node, pointed by p, in the
next field of the node q.

q->next=p

Start q

Data Next Data Next Data NULL

P X NULL

P a g e | 15 DS&OOPs
Deletion:

This operation is used to delete an item from the linked list. Deletion a node from the list is
even easier than insertion, as only one pointer value needs to be changed. Here again we have
three situations.
1. Deleting the first item
2. Deleting the last item
3. Deleting the meddle of the list
Algorithm for deleting the first ite m:
1. Store the address of the first node in a pointer variable, say P.
2. Move the head to the next node. head = head -> next
3. Free the node whose address is stored in the pointer variable P, free(P).
Start

5 Next 4 Next 7 NULL

P Before deletion

Start

4 Next 7 NULL

After deletion

Deleting the middle ite m:

Start node

Data Next Data Next Data Next Data NULL

q p
Algorithm:

1. Store the address of the preceding node in a pointer variable q. Node to be deleted
is marked as key node.
2. Store the address of the key node in a pointer variable p, so that it can be
freed subsequently.
3. Make the successor of the key node as the successor of the node pointed by q.
q->next = p->next
4. Free the node whose address is stored in the pointer variable
p. Free(p)

P a g e | 16 DS&OOPs
Deleting the last item:

Start node

Data Next Data Next Data Next

q
Data NULL

Algorithm: p

If(start->next == NULL)
Free(start)
Else
q=start;
while(q-> next != NULL)
q=q->next
p=q->next
free(p);
Display the elements in a linked list:

void display()
{
q=start;
while(q!=NULL)
printf(“%d”,q->data)
q=q->next
}
3. Explain about Circular linked list?
It is just like a linear or single linked list in which the next field of the last node contains the address
of the first node in the list . The nest field of the last node does not point to NULL rather it points
back to the beginning of the linked list. A queue data structure can be implemented using a circular
linked list with a single pointer “rear” as the front node can be accessed through the rear node.
Struct node
{
Int data;
Struct node *next;
} *start=NULL;
Insertion at end:
Insertion of a node at the start or end of a circular linked list identified by a pointer to the last node of
the linked list takes a constant amount of time.
Algorithm for a circular list is slightly different than the same algorithm for a singly connected
linked list because “NULL” is not encountered.

P a g e | 17 DS&OOPs
Start node

Data Next Data Next Data Next Data Next

Address of the
first node

rear P

Data Next Data Next Data Next Data Next

Algorithm:
If(rear==NULL)
Rear=p;
p->next =p;
return p;
else
rear->next = p;
p->next= rear->next;
rear=p;

Insertion at middle:
q start

Data Next Data Next Data Next Data Next

Data Next

p
Algorithm:
Node *insert(int *start, int x, int loc)
{
P=node(node*)malloc(sizeof(node));
If(start==NULL)
p->next=p
return(p)
q=head->next;
for(i=0; i < loc; i++) //loc is position of qth element q=q-
>next;

p->next=q->next;
q->next=p
return(p);
}

P a g e | 18 DS&OOPs
Deletion:
q start

Data Next Data Next Data Next Data Next

p
Algorithm:

Node *delete (int *head, int x, int loc)


{
If(head==NULL)
Printf(“Unerflow”);
Else If(start->next==start)
Free(p);
else
q=head->next;
for(i=0; i < loc; i++) //loc is position of qth element q=q-
>next;

p=q->next;
q->next=p->next;
free(p);
}
Display:

Algorithm:

Void display( node *rear)


{
Node *p;
If(rear!=NULL)
{
P=rear->next;
do
{
Printf(“%d”,p->next);
P=p->next;
}while(p!=rear->next);
}
}

P a g e | 19 DS&OOPs
4.Doubled linked list?

One of the most striking disadvantages of these lists is that the inability to traverse the list in
the backward.

In most of the real world applications it is necessary to reverse the list both in forward direction
and backward direction.

The most appropriate data structure for such an application is a doubly linked list.

A double linked list is one in which all nodes are linked together by multiple number of links
which help in accessing both the successor node and predecessor node form the given node
position. It provides bi-directional traversing.

Each node in a double linked list has two linked fields. These are used to point to the successor
node and predecessor nodes. Prev field holds the address of the previous node and next field holds
the address of the nest node.

Struct node Prev data next


{
Int data;
Struct node *prev, *next;
} *start=NULL;

Start node

NULL data next Prev data next Prev data NULL

Creating a node:

Step 1: create memory space for the new data

q=(node*)malloc(sizeof(node));

step 2: store x in the newly acquired node

q->data=x;

step 3: make previous and next field as NULL ;

q->prev=NULL; q->next=NULL

Initially start is NULL

Start NULL 5 NULL After insertion of 5


Start
P

NULL 5 next Prev 2 NULL After insertion of 2

P a g e | 20 DS&OOPs
Insertion at middle:

Insertion and deletion are two basic operations on such lists. Consider that a new node pointed to by
p is to be inserted after the node pointed to by q in a doubly linked list. Links of two nodes are alered
during insertion.

Start q

NULL 5 next Prev 11 next Prev 6 NULL

Prev 3 next

P
Start q

NULL 5 next Prev 11 next Prev 3 next Prev 6 NULL

Algorithm: Previous link

Void insertmid()
{
p=(node*)malloc(sizeof(node));
p->data=3;
p->next=q->next;
p->prev=q;
q->next=p;
if(p->next!=NULL)
p->next->prev=p;
}
Insertion at beginning:

Void insertbeg()
{
p=(node*)malloc(sizeof(node));
p->data=x
p->prev=NULL
p->next=start;
if( start!=NULL)
start ->prev=p;
}

P a g e | 21 DS&OOPs
Insertion at end:

Void insertend()
{
p=(node*)malloc(sizeof(node));
p->data=x
p->next=NULL;
q=start;
while(q->next!=NULL)
q=q->next;
p->prev=q;
q->next=p
}
Deletion of node:

When a node, pointed to by P is to be deleted then its predecessor node x and its successor node
y will be affected.

- Right link at x should be set to y.


- Left link at y should be set to x.
- Release the memory allocated to the node pointed to by p.

Start X Y

NULL 5 next Prev 11 next Prev 3 next Prev 6 NULL

P
Start X Y

NULL 5 Next Prev 11 next Prev 3 next Prev 6 NULL

P
C-instructions for deletions:

P->prev->next=P->next;

p->next->prev=P->prev;

free(P);

Display the elements in a linked list:

Algorithm:
void display()
{
q=start;

P a g e | 22 DS&OOPs
while(q!=NULL)
printf(“%d”,q->data)
q=q->next
}

5. Explain about QUEUE AND ITS OPERATIONS?

A Queue is an ordered collection of elements in which insertions are made at one end and
deletions are made at the other end.

The end at which insertions are made is referred to as the rear end, and the end from which
deletions are made is referred to as the front end.

The first element inserted will be the first element to be removed. So a queue is referred to as
First-In- First-Out (FIFO) list.

Operations:

1. Enqueue operation
2. Dequeue operation
3. Peek operation
4. Empty queue operation

1..Enqueue ope ration:

Enqueue is an operation used to add a new element in to a queue at the rear end. When
implementation the Enqueue operation overflow condition of the queue is to be checked.

Algorithm:

Enqueue()
Step 1: if(REAR==QSIZE-1) then

Print, “queue is overflow on enqueue”


Return

End of if structure

P a g e | 23 DS&OOPs
Step 2: if(FRONT==-1 && REAR==-1) then

Set FRONT=0 and REAR =0


Else

REAR=REAR+2

End of if structure

Step 3: print, enter the element


Step 4: read, QUEUE(REAR)

End ENQUEUE()

2. Dequeue operation:

Dequeue is an operation used to remove an element from the front end of the queue. When
implementing the dequeue operation, underflow condition of a queue is to be checked.

Algorithm:

DEQUEUE()

Step 1: if (if(FRONT==-1 && REAR==-1) then

Print, “queue is underflow on enqueue”

Return
End of if structure

Step 2: print, “the deueued value is , QUEUE(FRONT)

If (FRONT==REAR) then

Set FRONT =-1 and REAR =-1


Else

FRONT= FRONT+1

End of if structure

End Dequeue()
3. PEEK operation:
Peek is and operation used to display the element from the front of the queue, pointed by the FRONT
pointer without actually removing it.

Algorithm:

PEEK()
Step 1: if (if(FRONT==-1 && REAR==-1) then

Print, “queue is Empty”

Return

P a g e | 24 DS&OOPs
End of if structure

Step 2: print, “the top most value is,” QUEUE[FRONT]


End PEEK()

1. EMPTY queue:

If a queue contains no elements , it is referred as an empty queue.

Algorithm:

Step 1: if (if(FRONT==-1 && REAR==-1) then


Print, “queue is Empty”

Else

Print,” queue is not empty”

End of if structure
End ISEMPTY()

6. Write short notes on priority queues. (Nov 2012)


PRIORITY QUEUES
Priority queues are a kind of queue in which the elements are dequeued in priority order.
A priority queue is a collection of elements where each element has an associated
priority. Elements are added and removed from the list in a manner such that the element with
the highest (or lowest) priority is always the next to be removed. When using a heap
mechanism, a priority queue is quite efficient for this type of operation.

 Each element has a priority, an element of a totally ordered set (usually a number).

 More important things come out first, even if they were added later.

 Three types of priority. Low priority [10], Normal Priority [5] and High Priority [1]. 

 There is no (fast) operation to find out whether an arbitrary element is in the queue. 

ALGORITHM:

P a g e | 25 DS&OOPs
Priority Queue - Algorithms - Adjust

Adjust(i)
left = 2i, right = 2i + 1

if left <= H.size and H[left] > H[i]


then largest = left
else largest = i
if right <= H.size and H[right] > H[largest]
then largest = right
if largest != i
then swap H[largest] with H[i]
Adjust(largest)
Explanation

Adjust works recursively to guarantee the heap property. It compares the current node
with its children finding which, if either, has a greater priority. If one of them does, it will swap
array locations with the largest child. Adjust is then run again on the current node in its new
location.

Priority Queue - Algorithms - Insert

Insert(Key)
H.size = H.size + 1
i = H.size
while i > 1 and H[i/2] < Key
H[i] = H[i/2]
i = i/2
end while
H[i] = key
Explanation

The insert algorithm works by first inserting the new element (key) at the end of the
array. This element is then compared with its parent for highest priority. If the parent has a
lower priority, the two elements are swapped. This process is repeated until the new element
has found its place.

P a g e | 26 DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING DEPARTMENT OF ECE


Priority Queue - Algorithms - Extract

Extract()
Max = H[1]
H[1] = H[H.size]
H.size = H.size - 1
Adjust(1)
Return Max
Explanation

Extract works by removing and returning the first array element, the one of highest
priority, and then promoting the last array element to the first. Adjust is then run on the first
element so that the heap property is maintained.

Run Time Complexity

 È(lg n) time for Insert and worst case for Extract (where n is number of elements)

 È(lg n) average time for Insert

 Can construct a Heap from a list in È(lg n) where a Binary Search Tree takes È(n lg n)
Space Requirements

 All operations are done in place - space requirement at any given time is the number of
elements, n.


7. Define Stack? Explain the various operations in Stacks? (April 2012, April 2013)
STACK
A stack is an ordered collection of items where new items may be inserted or deleted only at
one end, called the top of the stack.
A stack is a data structure that keeps objects in Last- In-First-Out (LIFO)
order, Objects are added to the top of the stack
Only the top of the stack can be accessed.

Stacks have some useful terminology associated with them:


 Push To add an element to the stack 

 Pop To remove an element from the stock 

 Peek To look at elements in the stack without removing them

 LIFO Refers to the last in, first out behavior of the stack

 FILO Equivalent to LIFO

P a g e | 27 DS&OOPs
Stack

push pop

Simple representation of a stack:

Given a stack S=(a[1],a[2],.......a[n]) then we say that a1 is the bottom most element and element
a[i]) is on top of element a[i-1], 1<i<=n.

Implementation of stack:
1. Array (static memory)
2. linked list (dynamic memory)

Operations of stack is
I. PUSH operations
II. POP operations III.
PEEK operations
The Stack ADT
A stack S is an abstract data type (ADT) supporting the following three methods:
push(n) : Inserts the item n at the top of stack
pop() : Removes the top element from the stack and returns that top element. An error occurs
if the stack is empty.
peek() :Returns the top element and an error occurs if the stack is empty.

I. PUSH operation - Adding an element into a stack


Adding element into the TOP of the stack is called PUSH operation.

Check conditions :
TOP = N , then STACK FULL
where N is maximum size of the stack.

P a g e | 28 DS&OOPs
PUSH algorithm- Adding an element into stack

procedure add(item : items);


{add item to the global stack stack ; top is the current top of
stack and n is its maximum size}
begin
if top = n then stackfull;
top := top+1;
stack(top) := item;
end: {of add}
item / 6
Stack element Stack

PUSH top 6
operation
top 8 8
4 4
Implementation in C using array:
/* here, the variables stack, top and size are global variables
*/ void push (int item)
{
if (top == size-1)
printf(“Stack is Overflow”);
else
{
top = top + 1;
stack[top] = item;
}}
II. POP operation - Deleting an element from a stack.
Deleting or Removing element from the TOP of the stack is called POP operations.
Check Condition:
TOP = 0, then STACK EMPTY

POP algorithm- Deleting an element from a stack

procedure delete(var item : items);


{remove top element from the stack stack and put it in the item}
begin
if top = 0 then stackempty;
item := stack(top);
top := top-1;
end; {of delete}

P a g e | 29 DS&OOPs
item /
element 6

top 6 POP
8 operation
top 8
4
4
Stack
Stack
Implementation in C using array:
/* here, the variables stack, and top are global variables
*/ int pop ( )
{
if (top == -1)
{
printf(“Stack is Underflow”);
return (0);
}
else
{
return (stack[top--]);
}}
III. Peek Operation:
 Returns the item at the top of the stack but does not delete it.

 This can also result in underflow if the stack is empty.

item /
element 6

top top 6
6 PEEK
8 operation 8
4 4
Stack Stack
Algorithm:
PEEK(STACK, TOP)
BEGIN
/* Check, Stack is empty? */
if (TOP == -1) then
print “Underflow” and return 0.
Else
item = STACK[TOP] / * stores the top element into a local variable */
return item / * returns the top element to the user */

P a g e | 30 DS&OOPs
END

Implementation in C using array:


/* here, the variables stack, and top are global variables
*/ int pop ( )
{
if (top == -1)
{
printf(“Stack is Underflow”);
return (0);
}
else
{
return (stack[top]);
}}
Applications of Stack
1. It is very useful to evaluate arithmetic expressions. (Postfix Expressions)
2. Infix to Postfix Transformation
3. It is useful during the execution of recursive programs
4. A Stack is useful for designing the compiler in operating system to store local variables
inside a function block.
5. A stack (memory stack) can be used in function calls including recursion.
6. Reversing Data
7. Reverse a List
8. Convert Decimal to Binary
9. Parsing – It is a logic that breaks into independent pieces for further processing
10. Backtracking

8. EXPLAIN ABOUT APPLICATION OF STACK?

1. Towers of Honoi
2. Reversing a string
3. Balanced parenthesis
4. Recursion using stack
5. Evaluation of arithmetic expression

P a g e | 31 DS&OOP
Reversing a string

REVSTRING(STR:STRING)

i = integer

Step 1: push(null)

Step 2: for (i-0; STR[i]==NULL;i++)


Push(STR[i])

End of for loop

Step 3: while (POP(STR--)!=0)

End of while loop


End REVSTRING()

Recursion using stack:

push local data and return address onto stack


return by popping off local data and then popping off address and returning to it
return value can be pushed onto stack before returning, popped off by caller
Fact(int)

If(x<=1)

Return(1);

Else

Return(x*fact(x-1));

Infix to postfix conversion:

Algorithm:

INSTR contain infix expression & POSTSTR stores the resultant expression
Step 1: initialize the stack

Step 2: while (INSTR!=NULL)

Step 3: CH= get the character from INSTR

Step 4: if (CH== operand) then


Append CH into POSTSTR
Else if(CH==’(’) then

Push CH into the stack

P a g e | 32 DS&OOPS
Else if (CH==’)’) then

POP the data from the stack &append the data into POSTSTR
Else

while (precedence(top of stack)>=precedence(CH))

POP the data from the stack and append into


POSTSTR Step 5: push CH into the stack
Step 6: POP all the data from the stack & append the data into POSTSTR

Example:
Suppose the infix expression is to be converted into postfix.
a +b*c+(d*e+f)*g
A correct answer is a b c * + d e * f + g * +.

Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so nothing
is output and '*' is put on the stack. Next, c is read and output. Thus far,

The next symbol is a '+'. Checking the stack, pop a '*' and place it on the output, pop the other
'+', which is not of lower but equal priority, on the stack, and then push the '+'.

The next symbol read is an '(', which, being of highest precedence, is placed on the stack. Then d
is read and output.

Continue by reading a '*'. Since open parentheses do not get removed except when a closed
parenthesis is being processed, there is no output. Next, e is read and output.

P a g e | 33 DS&OOPS
The next symbol read is a '+'. We pop and output '*' and then push '+'. Then read and output

.
Now read a ')', so the stack is emptied back to the '('. Output a '+'.

Read a '*' next; it is pushed onto the stack. Then g is read and output.

The input is now empty, so we pop and output symbols from the stack until it is empty.

As before, this conversion requires only O(n) time and works in one pass through the input.
This algorithm does the right thing, because these operators associate from left to right.

P a g e | 34 DS&OOPs
9. Describe about Linked Stacks?
LINKED STACKS:
 A stack is a list with the restriction that inserts and deletes can be performed in only one
position, namely the end of the list called the top.

 The fundamental operations on a stack are push, which is equivalent to an insert, and
pop, which deletes the most recently inserted element.

 The most recently inserted element can be examined prior to performing a pop by use of
the top routine.

 A pop or top on an empty stack is generally considered an error in the stack ADT. On the
other hand, running out of space when performing a push is an implementation error but
not an ADT error.

 Stacks are sometimes known as LIFO (last in, first out) lists. The usual operations to
make empty stacks and test for emptiness are part of the repertoire, but essentially all
that you can do to a stack is push and pop.

Type declaration for linked list implementation of the stack ADT


typedef struct node *node_ptr;
struct node
{
element_type element;
ptrnode next;
};
typedef ptrnode STACK;
Creating a stack
It allocates memory for the given structure (header of the stack. It points to the element
at the front of the stack). The stack is emptied by calling make empty function.
STACK create_stack( void )
{
STACK S;
S = (STACK) malloc( sizeof( struct node ) );
if( S == NULL )

P a g e | 35 DS&OOPs
fatal_error("Out of space!!!");
makeempty(S);
return S;
}
Routine to test whether a stack is empty
This function checks whether the stack is empty or not. The function is_empty ()
makes the S->next to point to the header in case if the stack is empty.
int is_empty( stack s )
{
return( S->next == NULL );
}

Routine to empty the stack


If the stack is not empty, the stack is popped until it becomes empty. In other words, the
stack exists but the stack is empty.
void makeempty( STACK S )
{
if( S == NULL )
error("Must use create_stack first");
else
while(!Isempty(S))
pop(S);
}

Routine to push onto a stack


To push an element into the stack, allocate memory, insert the value and make S->next
to point to that element.

void push( element_type x, STACK S )


{
Ptrnode tmpcell;
tmpcell = (node_ptr) malloc( sizeof ( struct node ) );
if( tmpcell == NULL )
fatal_error("Out of space!!!");
else

P a g e | 36 DS&OOPS
{
tmpcell->element = x;
tmpcell->next = S->next;
S->next = tmpcell;
}
}
Routine to return the top element in a stack
This function returns the element in the top of the stack.
element_type top( STACK S )
{
if( !isempty( S ) )
return S->next->element;
error("Empty stack");
return 0;
}
Routine to pop from a stack
Check whether the stack is empty. Declare a pointer variable firstcell make it point to the
element that is to be deleted. If the stack is not empty the element pointed to by S->next should
be removed from the stack.
void pop( STACK S )
{
Ptrnode first_cell;
if( isempty( S ) )
error("Empty stack");
else
{
first_cell = S->next;
S->next = S->next->next;
free( first_cell );
}
}

P a g e | 37 DS&OOPs
10. Describe about Linked Queues?
Linked Queues
Like stacks, queues are lists. With a queue, however, insertion is done at one end, whereas
deletion is performed at the other end. The basic operations on a queue are enqueue, which
inserts an element at the end of the list (called the rear), and dequeue, which deletes (and
returns) the element at the start of the list (known as the front).
 Figure shows the abstract model of a queue. The queues can be implemented using
arrays or pointers.

 Queue is implemented using Singly Linked Lists, where the next pointer of the element at
the rear end is made to point to NULL.

Queue Model
The basic operations on a queue are enqueue, which inserts an element at the end of the
list (called the rear), and dequeue, which deletes (and returns) the element at the start of the list
(known as the front). Figure shows the abstract model of a queue.
Structure definition
Each node contains two fields. Every last node points to null.

struct node
{
element type element ;
ptr to node*next;
};
typedef node_ptr queue;
Function to check whether the queue is empty or not
This function is empty checks whether the queue is empty or not, It returns true, if the
queue is empty. It makes the q->next to point to NULL in case if the queue is empty.
int is_Empty (queue q)
{
return q->next= = NULL;
}

P a g e | 38 DS&OOPs
Creating a Queue
It allocates memory for the given structure (header of the queue. It points to the element
at the front of the queue). The queue is emptied by calling makeempty( ) function.
queue create queue (void)
{
queue q;
q=malloc (sizeof(struct node));
if(q= = null)
fatal error(“OUT OF SPACE”):
makeempty(q);
return q;
}
Function to empty the queue
If the queue is not empty, the elements in the queue are removed until the queue
becomes empty. In other words, the queue exists but the queue is empty.
void make empty(queue q)
{
if(q = =null)
error(“Must use create queue first”);
else
while (!isempty (q));
delete(q);
}
Function to insert an element into the queue
To insert an element into the queue, in the linked list implementation, it is possible only
at the rear end. Therefore the position of the last element (p) is found. The last element’s next
pointer points to NULL.
void insert (elementtype X, queue q)
{
ptr tonode tempcell;
p=q;
tempcell=malloc(sizeof (struct node));
if(tempcell==NULL)
fatalerror(“out of space”);
else

P a g e | 39 DS&OOPs
{
while (p->next!=NULL)
p=p->next;
tempcell->element=X;
tempcell->next=p->next;
p->next=tempcell;
}
}
Function to return the first element in the list
It checks whether the queue is empty. If it is not empty, it returns the element at the
front of the queue. int front(queue q)
{
if(!isempty (q))
return q->next->element;
else
fatal error(“empty queue”);
return 0;
}
Function to remove an element at the front of the queue (first)
Check whether the queue is empty. If the queue is not empty the element pointed to by
q-> next should be removed from the queue. Declare a pointer variable firstcell. Make it point to
the element that is to be deleted. Once the first element is removed, q->next should point to the
next element in the queue.
void delete(queue q)
{
ptr to node firstcell;
if (isempty (q))
error(“empty queue”);
else
{
firstcell=q->next;
q->next=q->next->next;
free(first cell);
}
}

Page 40
DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING
Question Bank

Unit- II

1. How does a Stack works? Explain the Algorithm for inserting and deleting an element in stack with .
diagrammatic representation (sep 21)
2. What IS doubly Linked List? Explain the Algorithm in detail for inserting a node to the left and deleting a node
from the doubly linked list. (sep 21) (jan 22)
3. What is Queue? Why it is known as FIFO? Write an algorithm to insert and delete an element from a simple
Queue (jan 22)
4. What is Doubly Linked List? Write an algorithm to insert and delete a node in Doubly Linked List. (Jan 22)
5. Distinguish the Stack and Queue and give the detail description about Queue operations (march 21)
6. Explain, using appropriate pseudo code, how an elements can be inserted and deleted in linked stack (march 21)
7. Write an algorithm for inserting a node at any position in a singly linked list. (Sep 20)
8. Explain the concept where insertion and deletion at either end. of the structure can be performed. (Sep 20)
9. Explain how stack is implemented using linked list representation (Sep 20)
10. How stack is used in Evaluation of Arithmetic expression? Justify with example. (nov 2019)
11. . Given single linked list containing set of data. From this. (nov 2019)
(a) Reverse the direction of links.
(b) For the list count the number of nodes.
12. Short notes on Priority queue (may 2019)

13. Write an algorithm for inserting an element into a circular queue and deleting an element from a circular
Queue.( Nov 2018)

2 Marks

1. Define abstract data type (ADT).


2. List the applications of stacks.
3. Define queue with example.
4. Give the difference between Stack and Queue
5. What is a non-linear' data structure? Give an example.
6. 'What is priority queue?
7. What is linked list? Point out its applications and advantages.
8. State an applications of queue and linked list.
9. What is meant by Doubly linked hst? Give an example
10. State the advantages of circular lists over doubly linked list.
11. How to test for a empty queue
12. In what way ENQUEUE. operation of circular Queue. differ from normal Queue?
13. Write an algorithm to traverse a single linked list
14. What is circular linked list? Give example.
15. List out the applications of linked list.
16. Differentiate post and pre traversal. .

Page 41 DS&OOPs

You might also like