• Nenhum resultado encontrado

DS & DAA Materials

N/A
N/A
Protected

Academic year: 2021

Share "DS & DAA Materials"

Copied!
108
0
0

Texto

(1)

Concept of Abstract Data Types

In general, for any organization data is vital (very important). So organizations don’t wish to make their data available to end users directly.They keep their data more confidential (secret or private). But end users need to access the data whenever necessary. Here the problem is, organizations wish to make their data confidential and end user wants to access the same data frequently.

So, companiesprovide a way, to users, to access those confidential data through some methods. Here methods are nothing but the actions that the user wishes to perform on the confidential data. That is, the end user is allowed to access the data through the methods provided only. Here the thing to be observed is that the end user only makes calls to the required methods but he doesn’t know the actual method definition. This is called as procedural abstraction.

One more thing to be observed here is, the data is kept as private and accessible through the provided methods only. So we can say this as data abstraction. In order to achieve all these, data and methods to access the data are to be encapsulated in to a single unit called as Abstract Data Type (ADT) or class. That is why we define classes as an abstract data types.

Data types:

The kind of data such as integer, float, char, string etc., which are tobe processed in our program to get the required output is called as data type. Theoperations that can be performed on data are based on the type of data. Datatypes can be classified into the following three types. They are,

a) Predefined data types b) Derived data types c) User defined data types. Pre-defined data types:

These are the data types supported by theprogramming languages. These are alsocalled as built-in or in-built or standard or reserved or basic or primary or primitive data types.Thesemay vary to one programming language to another. For example,

C : int , flat, char, double etc.

Java : byte, short, int, long, float, double, char, Boolean Derived data types:

These are the data types that are derived from thepredefined data types. Everyprogramming language supports few deriveddata types such as:

(2)

User Defined data types:

In solving real world problems, the pre-definedand derived data types may not suit as per the requirement. In such cases, theprogrammers need to create their own data types as pertheirrequirements. Suchkind of data types are called as user defined data types. Differentprogramming languages provide different concepts to create user defineddata types. For example to create user defined data types in “Java” we canuse:

Classes, Interfaces, enum Storage Structure and File Structure:

The representation of a particular datastructure in the primary memory (RAM) of a computer is called a storage structure. Whereas a storage structure representation in secondary memory (Hard disk) is called afile structure.

Data Structure:

Data can be organized in memory in different ways. Theorganization of data in memory in an efficient way is defined as data structure.Here efficient way refers to quickly and easily inserting, deleting, accessing datain memory. The official definition of data structure is as follows:

“A data structure is a triplet, that is, Data Structure DS = (D, F, A) whereD is set of data or domain, F is set of functions and A (axioms) is set of rules toimplement functions.

Example:

Domain (D) : Set of Integers ( 0, ± 1, ± 2, ± 3,……. ±n) Functions F :Set of Operations(+,-,*,/,%)

Axioms A :Set of rules that define how to do addition, subtraction,multiplication , division and modulo division.

Types of Data Structures:

Basically data structures can be classified into two types.They are, I. Primitive Data Structures

(3)

Primitive Data Structures:

The data structures that are atomic or indivisible arecalled primitive or fundamental data structures. These are the basic data types that areavailable in most of the programming languages. The primitive data structures are used torepresent single values.

Examples:

Integer: This is used to represent a number without decimal point. Eg: 201, 205

Float and Double: This is used to represent a number with decimal point. Eg: 6.6, 7.3

Character :This is used to represent single character Eg: ‘V’, ‘S’

String: This is used to represent group of characters. Eg: "I am Happy"

Boolean: This is used represent logical values either true or false. Eg: false (0) , true(1).

Non-Primitive Data Structures:

The data structures that are not atomic are callednon-primitive or composite. These are derived from primitive data structures. These datastructures are used to store group of values.The non-primitive data structures are againclassified into two types namely,

a) Linear data structures b) Non-Linear data structures Linear data structures:

In a linear data structure, the data items are arrangedin a linear order. The following are the linear data structures.

Arrays, Stacks,Queues,Linked Lists Non-Linear data structures:

In a non-linear data structure, the data items arenot in a definite order.The following are the non-linear data structures.

Trees,Graphs,Tables,Sets Homogenous Data Structure:

In homogenous data structures, all the elements are ofsame type. Example is array. Non-Homogenous Data Structure:

In non-homogenous structures, all the elements mayor may not be of the same type. Example is records.

Static Data Structure:

Static structures are ones whose sizes, structures and associated memory locations are fixed at compile time.

Dynamic Data Structure:

Dynamic structures are ones which expand or shrink as required during the program execution. Hence associate memory locations may change at runtime.

Pointers:

A Pointer is a variable which can store the address of another variable. Since pointers store addresses, they increase the speed of the program. Java does not support pointers. But C supports pointers. In C, like any variable or constant, we must declare a pointer before using it to store any variable’s address. The general form of a pointer variable declaration is:

(4)

dataType *var-name;

Here, datatype is any valid data type and var-name is the name of the pointer variable.The asterisk symbol(*) is used to declare a pointer. The following are the some of the valid pointerdeclarations. int *ip; double *dp; float *fp; char *cp; -Asymptotic Notations:

There are three types asymptotic notations which are useful to analyze an algorithm’s efficiency mathematically.

1. Big Oh(O) 2. Omega(Ω) 3. Theta(Ө) Big Oh(O):

The function f(n)=O(g(n)) if and only if there exist positive integers c and n0 such that

f(n)≤c*g(n) for all n, n≥n0.

Example:

The function 3n+2=O(n) as 3n+2 ≤ 4n for all n≥2.

We write O(1) to mean a computing time that is a constant. O(n) is called Linear, O(n2) is

called Quadratic, O(n3) is called Cubic and O(2n) is called Exponential.

If an algorithm takes time O(n), then it is faster than the algorithm that takes time O(n2).

Similarly, the algorithm that takes time O(n2) is better than the algorithm that takes time O(n3).

Omega(Ω):

The function f(n)= Ω(g(n)) if and only if there exist positive integers c and n0 such that

f(n)≥ c*g(n) for all n, n≥n0.

Example:

The function 3n+2= Ω(n) as 3n+2 ≥ 4n for all n≥1.

Theta(Ө):

The function f(n)= Ө(g(n)) if and only if there exist positive integers c1,c2 and n0 such that

c1g(n)≤ f(n) ≤ c2g(n)for all n, n≥n0.

Example:

(5)

1. What is Array? Explain its ADT Ans:

Definition:

An array is a finite, ordered and collection of homogeneous data elements. An array is finite because it contains only a limited number of elements, ordered as all the elements are stored one by one in contiguous locations of the computer memory in a linear order. As homogeneous all the elements of an array are of the same data type.

Basic Terminology:

Size:The number of elements in an array is called the size or length of the array. Type:The type of an array represents the kind of data type it is meant for.

Base: The base of an array is the address of the memory location where the first element of the array is located.

Index: All the elements in an array can be referenced by a subscript like A[i], this subscript is known as index. The index value is always an integer value. As each array element is identified by a subscript or index, an array element is also called subscripted or indexed variable.

Range of Indices: Indices of arrays elements may range from a lower bound to an upper bound called boundaries of an array.

Word:Word ‘w’ denotes the size of an element i.e., the amount of memory that is required to store an element of the array.

(6)

2. Explain One-Dimensional arrays and their address mapping and operations Ans:

Definition:

An array is a finite, ordered and collection of homogeneous data elements. An array is finite because it contains only a limited number of elements, ordered as all the elements are stored one by one in contiguous/consecutive locations of the computer memory in a linear order. As homogeneous all the elements of an array are of the same data type.

One-Dimensional Array:

If only one subscript/index is required to refer an element in an array, then the array is called as “One-Dimensional Array”.

Memory Allocation:

All the indexed variables of an array are allocated contiguous memory locations in computer’s memory. So memory representation of an array is simple.

Suppose, we have an array with n indexed variables, let the memory location of the first element is M. If each element requires one word, then the location of any element in the array can be calculated by using the following formula

Address (A[i]) =M+(i x w)

Physical Representation Eg:

Let M=4560 and w=1, calculate the address of A[0], A[2], A[7] Address (A[0]) = 4560+(0)x1 =4560 Address (A[2]) = 4560 +(2)x1 = 4562 Address (A[7]) = 4560 +(7)x1 = 4567 Operations:

Various operations that can be performed on an array are like Traversing, Sorting, Searching, Insertion, Deletion and Merging.

Traversing:

This operation is used to visit all elements in an array. Sorting:

(7)

Searching:

Thisoperation is applied to search an element of interest in an array. Insertion:

This operation is used to insert an element into an array. Deletion:

This operation is used to delete a specific element from an array.

3. Explain Multi-Dimensional arrays and their address mapping and operations Ans:

Definition:

An array is a finite, ordered and collection of homogeneous data elements. An array is finite because it contains only a limited number of elements, ordered as all the elements are stored one by one in contiguous locations of the computer memory in a linear order. As homogeneous all the elements of an array are of the same data type.

Multi-Dimensional Array:

If elements are represented using more than one index/subscript, then the array is called as “Multi-Dimensional Array”. Two dimensional arrays are a collection of homogeneous elements in which elements are ordered in rows and columns.

Eg:

Consider an array of size mxn, where m is the no.of rows and n is the no.of columns as follows. a00 a01 a02 . . . . a0n a10 a11 a12 . . . . a1n . . . . . . . . am0 am1 am2 . . . . amnmxn

The subscript ij of any element represents ith row and jth column.

Memory Representation:

Like one-dimensional arrays, two-dimensional arrays are also stored in contiguous memory locations. There are two conventions of storing two-dimensional array elements in the memory.

1. Row-Major Order 2. Column-Major Order Row-Major Order:

The elements of a two-dimensional array are stored in row-by-row basis, that is all the elements in the first row, then in the second row and so on.

Column-Major Order:

The elements of a two-dimensional array are stored in column-by-column basis, that is all the elements in the first column are stored in their order of rows, then in the second column and so on. Eg: a00 a01 a02 a10 a11 a12 a20 a21 a22 3X3

(8)

Memory Representation Referencing an element:

To refer an element in a two-dimensional structure, we need two index values one for row another for column. The indexing formula of row-major order is different from column-major order.

Let us assume that we have an array with mxn elements. Row-Major Order:

Address(aij) = 1+(ixn)+j

Eg: Address(a21) = 1+(2x3)+1 = 6+1+1 = 8

If the base address is M, then the above formula can be modified as follows. Address(aij) = M+(ixn)+j Eg: Address(a21) = 4560+((2x3)+1 = 4560+6+1 = 4567 Column-Major Order: Address(aij) = 1+(jxm)+i Eg: Address(a21) = 1+(1x3)+2 = 3+2+1 = 6

If the base address is M, then the above formula can be modified as follows. Address(aij) = M+(jxm)+i

Eg: Address(a21) = 4560+(1x3)+2

(9)

4. What is Linked List? Explain Single Linked Linear List Ans:

A linked list is an ordered collection of finite, homogeneous data elements called nodes. Unlike arrays, linked lists are dynamic structures as nodes are created whenever we require. The amount of memory required can be varied during its use.

In Linked Lists, the adjacency is maintained by using links or pointers. A link or pointer is the address of the subsequent(next/previous) element in the list. So, we need to maintain both data and link in a node. Thus, a node consists of two parts Data and Link. Data part of a node holds the user's data and Link part of the node holds the address value of its next/previous node in the list.

Single Linked List:

In single linked list, each node contains only one link which points to the next node in the list. We maintain a pointer called Headptr to point the very first node of the list.

Example:

In the above example, we have five nodes from N1 to N5. The first node is called as Head Node and last node is called as Tail Node. First node points to second, second points to third and so on. Tail Node always points to null which indicates there is no more node in the list. In single-linked list, we can travel only in one direction that is from Head Node to Tail Node. We can move only to the next node not to the previous node of the list. That is why it is called as one-way list.

Operations:

addNewNode (data):

This operation adds a new node to the list with the given data. delete (index):

This operation deletes an existing node from the list at given index position. size():

This operation gives the size i.e., how many nodes are there in the list. insert (index, data):

This operation inserts a new node to the list at a given index position with a given data value.

traversal():

This operation gathers data from each node in the list starting from head to tail node and displays the data.

(10)
(11)

C++ Program Code: #include<iostream.h> class Node { public: int data; Node *next; }; class SingleLinkedLinearList { private: Node *headptr; public: SingleLinkedLinearList() { headptr=NULL; } int addNewNode(int d) { if(headptr==NULL) {

headptr = new Node(); headptr->data=d; headptr->next=NULL; } else { Node *x = headptr; while(x->next!=NULL) x = x->next; x->next = new Node(); x = x->next; x->data = d; x->next = NULL; } return 1; }

int deleteNode(int index) {

if(index <1 || index > size() ) return 0; Node *x = headptr; if(index==1) headptr=headptr->next; else { int i=1;

(12)

while (i<index-1) { i++; x=x->next; } x->next=x->next->next; } return true; }

int insert(int index, int d) { if(index< 1 || index>size()) return false; else { if(index == 1) {

Node *temp = new Node(); temp->data=d; temp->next=headptr; headptr=temp; return true; } else { Node *x = headptr; int i=1; while (i<index-1) { i++; x=x->next; }

Node *temp = new Node(); temp->data =d; temp->next =x->next; x->next = temp; return true; } } } int size() { int count=0; Node *x = headptr; while(x!=NULL){ count++;

(13)

} return count; } void traverse() { Node *x; x = headptr; while(x!=NULL) { cout<<x->data<<" "; x = x->next; } } }; void main( ) { SingleLinkedLinearList slll; int quit=0;

int ch, data, index; while(!quit) {

cout<<"\n---"<<endl; cout<<"Single-Linked Linear List"<<endl; cout<<"---"<<endl; cout<<"1.ADD NEW NODE"<<endl; cout<<"2.INSERT NEW NODE"<<endl; cout<<"3.DELETE NODE"<<endl; cout<<"4.TRAVERSE"<<endl; cout<<"5. EXIT"<<endl;

cout<<"---"<<endl; cout<<"Enter Your Choice: "; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(slll.addNewNode(data))

cout<<"Item Added to the list"; else cout<<"Addition Failed...!"; break; case 2: cout<<"Enter Data: "; cin>>data; cout<<"Enter Index: "; cin>>index; if(slll.insert(index,data))

(14)

cout<<"Item Inserted into the List"; else cout<<"Insertion Failed...!"; break; case 3: cout<<"Enter Index: "; cin>>index; if(slll.deleteNode(index))

cout<<"Item Deleted from the list"; else

cout<<"Deletion Failed...!"; break;

case 4:

cout<<"\n---"; cout<<"\nElements in the list: ";

slll.traverse(); cout<<"\n---"; break; case 5: quit=1; break; default: cout<<"Invalid Choice...!"; } } }

(15)

5. What is Linked List? Explain Double Linked Linear List Ans:

A linked list is an ordered collection of finite, homogeneous data elements called nodes. Unlike arrays, linked lists are dynamic structures as nodes are created whenever we require. The amount of memory required can be varied during its use.

In Linked Lists, the adjacency is maintained by using links or pointers. A link or pointer is the address of the subsequent(next/previous) element in the list. So, we need to maintain both data and link in a node. Thus, a node consists of two parts Data and Link. Data part of a node holds the user's data and Link part of the node holds the address value of its next/previous node in the list.

Double Linked List:

In double linked list, each node contains two linksone points to the next node another points to the previous node in the list. We maintain a pointer called Headptr to point the very first node of the list.

Example:

In the above example, we have four nodes from N1 to N4. The first node is called as Head Node and last node is called as Tail Node. First node points to second, second points to third and so on. The left link of head node and right link of tail node points to null. It indicates that there is no previous node to head and no next node to tail node. In double-linked list, we can travel in either directions that is from Head Node to Tail Node and Tail Node to Head Node. That is why it is called as two-way list.

Operations:

addNewNode (data):

This operation adds a new node to the list with the given data. delete (index):

This operation deletes an existing node from the list at given index position. size():

This operation gives the size i.e., how many nodes are there in the list. insert (index, data):

This operation inserts a new node to the list at a given index position with a given data value.

traversal():

This operation gathers data from each node in the list starting from head to tail node and displays the data.

(16)
(17)

C++ Program Code: #include<iostream.h> class Node { public: int data;

Node *next, *previous; }; class DoubleLinkedLinearList { Node *headptr; public: DoubleLinkedLinearList() { headptr=NULL; } int addNewNode(int d) { if(headptr==NULL){ headptr=new Node(); headptr->data=d; headptr->previous = NULL; headptr->next=NULL; } else { Node *x=headptr; while(x->next!=NULL) x=x->next; x->next=new Node(); x->next->previous = x; x=x->next; x->data=d; x->next=NULL; } return 1; } int size() { int count=0; Node *x = headptr; while(x!=NULL){ count++; x=x->next; } return count; }

(18)

void traverse() { Node *x=headptr; while(x!=NULL){ cout<<x->data<<" "; x=x->next; } }

int deleteNode(int index) { if(index<1||index>size()) return 0; else { if(index==1) { headptr=headptr->next; if(headptr!=NULL) headptr->previous=NULL; } else { int i=1; Node *x=headptr; while(i<index) { x=x->next; i++; } x->previous->next=x->next; if(x->next!=NULL) x->next->previous = x->previous ; } } return 1; }

int insert(int index, int d) { if(index<1||index>size()) return 0; else { if(index==1) {

Node *temp=new Node(); temp->data=d;

(19)

headptr->previous=temp; headptr=temp; } else { int i=1; Node *x = headptr; while(i<index) { x=x->next; i++; }

Node *temp=new Node(); temp->data=d; temp->previous = x->previous ; temp->next=x; x->previous->next = temp; x->previous = temp; } } return 1; } }; void main( ) { DoubleLinkedLinearList dlll; int quit=0;

int ch, data, index; while(!quit) {

cout<<"\n---"<<endl; cout<<"Double-Linked Linear List"<<endl; cout<<"---"<<endl; cout<<"1.ADD NEW NODE "<<endl; cout<<"2.INSERT NEW NODE "<<endl; cout<<"3.DELETE NODE "<<endl; cout<<"4.TRAVERSE "<<endl; cout<<"5. EXIT "<<endl; cout<<"---"<<endl; cout<<"Enter Your Choice: ";

cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(dlll.addNewNode(data))

(20)

else cout<<"Addition Failed...!"; break; case 2: cout<<"Enter Data: "; cin>>data; cout<<"Enter Index: "; cin>>index; if(dlll.insert(index,data))

cout<<"Item Inserted into the List"; else cout<<"Insertion Failed...!"; break; case 3: cout<<"Enter Index: "; cin>>index; if(dlll.deleteNode(index))

cout<<"Item Deleted from the list"; else

cout<<"Deletion Failed...!"; break;

case 4:

cout<<"\n---"; cout<<"\nElements in the list: ";

dlll.traverse(); cout<<"\n---"; break; case 5: quit=1; break; default: cout<<"Invalid Choice...!"; break; } } }

(21)

6. What is Linked List? Explain Circular Linked List using Single linked list Ans:

A linked list is an ordered collection of finite, homogeneous data elements called nodes. Unlike arrays, linked lists are dynamic structures as nodes are created whenever we require. The amount of memory required can be varied during its use.

In Linked Lists, the adjacency is maintained by using links or pointers. A link or pointer is the address of the subsequent(next) element in the list. So, we need to maintain both data and link in a node. Thus, a node consists of two parts Data and Link. Data part of a node holds the user's data and Link part of the node holds the address value of its next/previous node in the list.

CircularLinked List:

A linked list where the last node points the header node is called the ‘Circular Linked List’. A circular list doesn't have definite head and definite tail nodes. Any Node in the list can be chosen as Head and node before that as Tail. If there are more than one Node in the list, then every Node will have next Node. If there is only one Node in the list that itself is the head and tail. The tail Node in the circular list points to the head Node.

Example:

Operations:

addNewNode (data):

This operation adds a new node to the list with the given data. delete (index):

This operation deletes an existing node from the list at given index position. size():

This operation gives the size i.e., how many nodes are there in the list. insert (index, data):

This operation inserts a new node to the list at a given index position with a given data value.

traversal():

This operation gathers data from each node in the list starting from head to tail node and displays the data.

(22)
(23)

#include<iostream.h> class Node { public: int data; Node *next; }; class SingleLinkedNonLinearList { private: Node *headptr; public: SingleLinkedNonLinearList() { headptr=NULL; } int addNewNode(int d) { if(headptr==NULL) {

headptr = new Node(); headptr->data=d; headptr->next=headptr; } else { Node *x = headptr; while(x->next!=headptr) x = x->next;

x->next = new Node(); x = x->next; x->data = d; x->next = headptr; } return 1; }

int deleteNode(int index) {

if(index <1 || index > size() ) return 0; Node *x; x = headptr; if(index==1) { if(headptr->next==headptr) headptr=NULL; else

(24)

x = headptr; while(x->next!=headptr) x = x->next; x->next = headptr->next; headptr=headptr->next; } else { int i=1; while (i<index-1) { i++; x=x->next; } x->next=x->next->next; } return 1; }

int insert(int index, int d) { if(index< 1 || index>size()) return 0; else { if(index == 1) {

Node *temp = new Node(); temp->data=d; temp->next=headptr; Node *x = headptr; while(x->next!=headptr) x = x->next; x->next = temp; headptr=temp; } else { Node *x = headptr; int i=1; while (i<index-1) { i++; x=x->next; }

(25)

temp->next =x->next; x->next = temp; } return 1; } } int size() { int count=0; Node *x = headptr; while(x!=NULL) { count++; x=x->next; if(x==headptr) break; } return count; } void traverse() { Node *x = headptr; while(x!=NULL) { cout<<x->data<<" "; x = x->next; if(x==headptr) break; } } }; void main( ) { SingleLinkedNonLinearList slnll; int quit=0;

int ch, data, index; while(!quit) {

cout<<"\n---"<<endl; cout<<"Single-Linked Non Linear List"<<endl; cout<<"---"<<endl; cout<<"1.ADD NEW NODE "<<endl; cout<<"2.INSERT NEW NODE "<<endl; cout<<"3.DELETE NODE "<<endl; cout<<"4.TRAVERSE "<<endl; cout<<"5. EXIT "<<endl; cout<<"---"<<endl;

(26)

cout<<"Enter Your Choice: "; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(slnll.addNewNode(data))

cout<<"Item Added to the list"; else cout<<"Addition Failed...!"; break; case 2: cout<<"Enter Data: "; cin>>data; cout<<"Enter Index: "; cin>>index; if(slnll.insert(index,data))

cout<<"Item Inserted into the List"; else cout<<"Insertion Failed...!"; break; case 3: cout<<"Enter Index: "; cin>>index; if(slnll.deleteNode(index))

cout<<"Item Deleted from the list"; else

cout<<"Deletion Failed...!"; break;

case 4:

cout<<"\n---"; cout<<"\nElements in the list: ";

slnll.traverse(); cout<<"\n---"; break; case 5: quit=1; break; default: cout<<"Invalid Choice...!"; break; } } }

(27)

Ans:

Arrays

Linked Lists

Array is a collection of elements having same data type with common name.

Linked list is an ordered collection of elements which are connected by links/pointers.

An array can be accessed either Sequentially or Randomly. That is using a subscript, we can access any element of an array.

In linked list, elements can’t be accessed randomly but can be accessed only Sequentiallyone after another.

In array, elements are stored in consecutive memory locations.

In linked list, elements can be stored at any available place as address of node is stored in previous node.

Insertion and deletion takes more time in array as elements are stored in consecutive memory locations.

Insertion & deletion are fast and easy in linked list as only value of pointer is needed to change. In array, memory is allocated at compile time

i.e. Static Memory Allocation.

In linked list, memory is allocated at run time i.e. Dynamic Memory Allocation.

In array, each element is independent, no connection with previous element or with its location.

In Linked list, location or address of elements is stored in the link part of previous element/node. In array, no pointers are used like linked list

so no need of extra space in memory for pointer.

In linked list, adjacency between the elements are maintained using pointers or links, so pointers are used and for that extra memory space is needed.

(28)

Ans: Definition:

A Stack is an ordered collection of homogeneous data elements where the insertion and deletion operations take place at only one end. Addition of items on to the stack is called ‘PUSH’ operation and deletion of items from the stack is called ‘POP’ operation. Each element in the stack is called ‘ITEM’, the maximum number of elements that a stack can store is called ‘SIZE’ of the stack.

Stack is a linear data structure that allows addition and deletion of items through a common end called ‘TOP END’ of the stack. The other end of the stack is sealed. In stack data structure, the item that is added last will be served first. That is why a stack is also called as LIFO(Last-In-First-Out) data structure.

Stack data structures are used when the item that is added last need to be served first. A stack can be visualized as a vertical structure where bottom is sealed and top is opened.

In the above representation, the maximum size of the stack is 8. That is we can store a maximum of 8 items on to the stack.

Representation of Stacks:

There are two ways of representing Stack data structure. 1. Using Arrays

2. Using Linked List Operations:

PUSH : This operation is used to insert an item onto a stack POP : This operation is used to remove an item from a stack STATUS : This operation is used to know the present state of a stack

(29)

9. What is Stack Data Structure? Explain how Stack is implemented using Arrays Ans:

A Stack is an ordered collection of homogeneous data elements where the insertion and deletion operations tale place at only one end. Addition of items on to the stack is called ‘PUSH’ operation and deleting items from the stack is called ‘POP’ operation. Each element in the stack is called ‘ITEM’, the maximum number of elements that a stack can store is called ‘SIZE’ of the stack.

Stack is a linear data structure that allows addition and deletion of items through a common end called ‘TOP END’ of the stack. The other end of the stack is sealed. In stack data structure, the item that is added last will be served first. That is why a stack is also called as LIFO(Last-In-First-Out) data structure.

Stack data structures are used when the item that is added last need to be served first. A stack can be visualized as a vertical structure where bottom is sealed and top is opened.

In the above representation, the maximum size of the stack is 8. That is, we can store a maximum of 8 items on to the stack.

Stack Representation using Arrays:

A Stack data structure can be represented using arrays. We perform stack operations Push and Pop by maintaining the top value to point to the topmost element position of the stack.

Initially TOP points to one position less than the lower bound i.e., 0. Here the stack is said to be in Empty state.

(30)

When we Push(add) an item onto the stack for the very first time, the item will be placed at bottom most position of the stack. Every new item will be placed on top of the previous item on the stack. Once the TOP reaches the upper bound, then no more items can be added on to the stack, here the stack is said to be in full state.

Example:

. . .

When we Pop(delete) an item from the stack for the very first time, the top most item will be popped out. Every pop operation will pop the top most item from the stack until the stack becomes empty.

Example:

. . . Underflow Condition (Empty State):

The stack is said to be in underflow condition when TOP points to one position less than the lower bound of the stack.

TOP = -1

Overflow Condition (Full State):

The stack is said to be in overflow condition when TOP reaches upto the upper bound of the stack.

TOP = SIZE-1 Operations:

PUSH : This operation is used to insert an item onto a stack POP : This operation is used to remove an item from a stack STATUS : This operation is used to know the present state of a stack

(31)
(32)

C++ Program Code: #include<iostream.h> int const SIZE=8; class Stack { public: int a[8]; int top; Stack() { top=-1; }

int push(int data) { if(top>=SIZE-1) return 0; else { top++; a[top]=data; return 1; } } int pop() { if(top<0) return 0; else{

cout<<"Item Popped: "<< a[top]; top--; return 1; } } void status( ) { if(top<0) cout<<"Stack is Underflow"; else if(top>=SIZE-1) cout<<"Stack is Overflow"; else

cout<<"There is vacancy in the Stack"; }

(33)

void main( ) { Stack s; int ch, data; int quit=0; while(!quit) { cout<<"\n---"; cout<<"\n STACK "; cout<<"\n---"; cout<<"\n 1.PUSH "; cout<<"\n 2.POP "; cout<<"\n 3.STAUTS "; cout<<"\n 4.EXIT "; cout<<"\n---"; cout<<"\nEnter Your Choice:"; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(s.push(data))

cout<<"Item Pushed on to the Stack"; else cout<<"Stack is Overflow...!"; break; case 2: if(!s.pop()) cout<<"Stack is Underflow...!"; break; case 3: s.status(); break; case 4: quit=1; break; default: cout<<"Invalid Choice...!"<<endl; } } }

(34)

10. What is Stack Data Structure? Explain how Stack is implemented using Linked List Ans:

A Stack is an ordered collection of homogeneous data elements where the insertion and deletion operations tale place at only one end. Addition of items on to the stack is called ‘PUSH’ operation and deleting items from the stack is called ‘POP’ operation. Each element in the stack is called ‘ITEM’, the maximum number of elements that a stack can store is called ‘SIZE’ of the stack.

Stack is a linear data structure that allows addition and deletion of items through a common end called ‘TOP END’ of the stack. The other end of the stack is sealed. In stack data structure, the item that is added last will be served first. That is why a stack is also called as LIFO(Last-In-First-Out) data structure.

Stack Representation using Linked List:

Array representation of stacks are useful only when we need fixed sized stacks. In several applications, the size of the stack may vary during program’s execution. In this case, we represent stack data structure using a linked list structure. The data structure linked list is sufficient to represent a stack.

In the linked representation, the first node of the list is the top of the stack and the last node is the bottom of the stack. Here SIZE is not required as we are using dynamic structure. Example:

Initially TOP points to null which indicates stack is Empty.

(35)

Everytime we POP an element from the stack, the item will be deleted at front i.e., at TOP position.

Underflow Condition (Empty State):

The stack is said to be in underflow condition when TOP points to null which indicates there is no item on the stack.

TOP = null

Overflow Condition (Full State):

In this implementation stack never faces the problem of overflow, because we use dynamic memory allocation for the items.

Operations:

PUSH : This operation is used to insert an item onto a stack POP : This operation is used to remove an item from a stack STATUS : This operation is used to know the present state of a stack

(36)

C++ Program Code: #include<iostream.h> class Node { protected: int data; Node *next; }; class Stack { private: Node *top; public: Stack() { top=NULL; } void status() { if(top==NULL) cout<<"Stack is Empty"; else { int count=0; Node *ptr = top; while(ptr!=NULL) { count++; ptr = ptr->next; } cout<<"No.of Nodes:"<<count; } }

(37)

x->data=item; x->next=top; top=x; return 1; } int pop() { if(top==NULL) return 0; else {

cout<<"Itemp Popped: "<<top.data; top = top->next; return 0; } } }; void main( ) { Stack s; int ch, data; int quit=0; while(!quit) { cout<<"\n---"; cout<<"\n STACK "; cout<<"\n---"; cout<<"\n 1.PUSH "; cout<<"\n 2.POP "; cout<<"\n 3.STATUS "; cout<<"\n 4.EXIT "; cout<<"\n---"; cout<<"Enter Your Choice:"; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(s.push(data))

cout<<"Item Pushed on to the Stack"; else cout<<"Stack is Overflow...!"; break; case 2: if(!s.pop()) cout<<"Stack is Underflow...!"; break; case 3: s.status();

(38)

break; case 4: quit=1; break; default: cout<<"Invalid Choice...!"); } } }

11. Give brief note on applications of Stack data structure Ans:

The stack data structure can be used in several areas. The following are some of the important applications.

Evaluation of Arithmetic Expressions:

An arithmetic expression consists of operands and operators. Operands are variables or constants and operators are of various kinds such as addition, subtraction, multiplication, division, modulo division etc. Each expression contains some brackets to specify the order of execution.

Eg: ((A+B)*(C/D))*(E%F)- G

Here the problem is to check the expression is in correct format or not. For this, we scan character by character and try to push the open bracket onto the stack and pop when we identify a close bracket. After reaching the last character of the expression, if the stack is empty, then the expression is in correct format, otherwise it is not.

Conversion of arithmetic expression into different notation:

The arithmetic expressions are combinations of various operands and operators. These expressions can be converted from one notation to another using stack data structure.

Eg: A+B - (infix) +AB - (prefix) AB+ - (postfix) Implementation of Recursion:

Recursion is an important aspect in programming. A function is termed recursive if the function calls itself.

Eg: factorial(n) { if n=0 then fact = 1 else fact = n*factorial(n-1) end if return fact } Towers of Hanoi:

(39)

In the Towers of Hanoi problem, we are given n disks and three towers. The disks are initially stacked on tower 1 in decreasing order of size from bottom to top. We are to move the disks to tower 2 one disk at a time, such that no disk is ever on top of a smaller one.

To get the largest disk to the bottom of tower 2, we move the remaining n-1disks to tower 3 and then move the largest to tower 2. Now we are left with the task of moving the n-1 disks from tower 3 to tower 2. To perform this task, we can use towers 1 and 2.

Tower 1 Tower 2 Tower 3

12. What is Queue Data Structure? Explain its ADT Ans:

A Queue is an ordered collection of homogeneous data elements where the insertion and deletion operations take place at two different ends. Insertion of items takes place at one end called ‘Rear End’ and deletion of items takes place at another end called ‘Front End’. Inserting an element into a queue is called ‘Enqueue’ and deleting an element from the queue is called ‘Dequeue’ operations.

An element in a queue is termed as ‘ITEM’, the number of elements that a queue can accommodate is termed as ‘LENGTH’ of the queue.

The Queue data structure is used in situations where first added item need to be served first. The data in a queue is processed in the same order as they added to the queue. That is why this data structure is known as First-In-First-Out (FIFO) data structure.

Addition of items to a Queue is possible only when the Queue is not full. Deletion of items from a Queue is possible only when the Queue is not empty.

Representation of Queues:

There are two ways of representing Queue data structure. 1. Using Arrays

2. Using Linked List Operations:

Enqueue : Inserts an item into the queue Dequeue : Deletes an item from the queue

(40)

13. What is Queue Data Structure? Explain how queue is implemented using arrays Ans:

A Queue is an ordered collection of homogeneous data elements where the insertion and deletion operations take place at two different ends. Insertion of items takes place at one end called ‘Rear End’ and deletion of items takes place at another end called ‘Front End’. Inserting an element into a queue is called ‘Enqueue’ and deleting an element from the queue is called ‘Dequeue’ operations.

An element in a queue is termed as ‘ITEM’, the number of elements that a queue can accommodate is termed as ‘LENGTH’ of the queue.

The Queue data structure is used in situations where first added item need to be served first. The data in a queue is processed in the same order as they added to the queue. That is why this data structure is known as First-In-First-Out (FIFO) data structure.

We maintain two pointers FRONT and REAR to point to both ends. While adding items to a Queue, the Rear End of the Queue increases and while deleting items from the Queue the Front End increases. Addition of items to a Queue is possible only when the Queue is not full. Deletion of items from a Queue is possible only when the Queue is not empty.

Representation of Queue using Arrays:

Queue data structure can be implemented using a one-dimensional array. Array implementation is useful where a queue of fixed size is required. We maintain two pointers FRONT and REAR to point to both ends. While adding items to a Queue, the Rear End of the Queue increases and while deleting items from the Queue the Front End increases.

Key Points:

 Initially both FRONT and REAR point to -1 which indicates that the queue is empty.

(41)

 Thereafter, each addition of item will increase the value of REAR, each deletion of item increases the value of FRONT.

Underflow Condition:

When FRONT < 0 or REAR < 0, the queue is said to be in underflow(empty) condition. Overflow Condition:

When REAR = LENGTH-1, the queue is said to be in overflow(full) condition. Example:

Operations:

Enqueue : Inserts an item into the queue Dequeue : Deletes an item from the queue

(42)

Program:

#include<iostream.h> const int LENGTH=8; class Queue

{ private:

int a[LENGTH]; int front, rear; public: Queue() { front=-1; rear=-1; }

int enqueue(int data) { if(rear==LENGTH-1) return 0; else { rear++; a[rear]=data; if(rear==0) front=0; return 1; } } int dequeue() { if(front<0) return 0; else {

(43)

front=rear=-1; else front++; return 1; } } }; void main( ) { Queue q; int ch, data; int quit=0; while(!quit){ cout<<"\n---"; cout<<"\n QUEUE "; cout<<"\n---"; cout<<"\n 1.ENQUEUE "; cout<<"\n 2.DEQUEUE "; cout<<"\n 3.EXIT "; cout<<"\n---"; cout<<"\nEnter Your Choice:"; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(q.enqueue(data))

cout<<"Item Added into the Queue"; else cout<<"Queue is Overflow...!"; break; case 2: if(!q.dequeue()) cout<<"Queue is Underflow...!"; break; case 3: quit=1; break; default: cout<<"Invalid Choice...!"; break; } } }

(44)

14. What is Queue Data Structure? Explain how queue is implemented using linked list Ans:

A Queue is an ordered collection of homogeneous data elements where the insertion and deletion operations take place at two different ends. Insertion of items takes place at one end called ‘Rear End’ and deletion of items takes place at another end called ‘Front End’. Inserting an element into a queue is called ‘Enqueue’ and deleting an element from the queue is called ‘Dequeue’ operations.

An element in a queue is termed as ‘ITEM’, the number of elements that a queue can accommodate is termed as ‘LENGTH’ of the queue.

The Queue data structure is used in situations where first added item need to be served first. The data in a queue is processed in the same order as they added to the queue. That is why this data structure is known as First-In-First-Out (FIFO) data structure.

We maintain two pointers FRONT and REAR to point to both ends. While adding items to a Queue, the Rear End of the Queue increases and while deleting items from the Queue the Front End increases. Addition of items to a Queue is possible only when the Queue is not full. Deletion of items from a Queue is possible only when the Queue is not empty.

Representation of Queue using Linked List:

A Linear Queue can be represented as a Linked List. For this we need two variables front and rear to keep track of the two ends of the Queue. There are two possibilities for binding these two variables to the ends of the Linked list. The nodes can be linked from front to rear or rear to front. But linking the nodes from front to rear is more efficient for deletions.

Example:

(45)

Operations:

Enqueue : Inserts an item into the queue Dequeue : Deletes an item from the queue Underflow Condition:

When FRONT = null or REAR = null, the queue is said to be in underflow(empty) condition.

Overflow Condition:

There is no chance of overflow condition, because we are using dynamic structure.

(46)

Program: #include<iostream.h> class Node { public: int data; Node *next; }; class Queue { private:

Node *front, *rear; public: Queue() { front=NULL; rear=NULL; }

int enqueue(int item) {

if(rear==NULL) {

rear = new Node(); rear->data=item; rear->next=NULL; front=rear; return 1; } else { rear->next=new Node(); rear=rear->next; rear->data=item; rear->next=NULL;

(47)

} } int dequeue() { if(front==NULL||rear==NULL) return 0; else {

cout<<"Item Deleted: "<<front->data; front = front->next; if(front==NULL) rear=NULL; return true; } } }; void main( ) { Queue q; int ch,data; int quit=false; while(!quit){ cout<<"\n---"; cout<<"\n QUEUE "; cout<<"\n---"; cout<<"\n 1.ENQUEUE "; cout<<"\n 2.DEQUEUE "; cout<<"\n 3.EXIT "; cout<<"\n---"; cout<<"\nEnter Your Choice:"; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(q.enqueue(data))

cout<<"Item Added into the Queue"; else cout<<"Queue is Overflow...!"; break; case 2: if(!q.dequeue()) cout<<"Queue is Underflow...!"; break; case 3:

(48)

quit=true; break; default: cout<<"Invalid Choice...!"; break; } } }

15. What is Circular Queue? Explain how queue is implemented using arrays Ans:

In a linear queue, if the REAR reaches the last position of the queue, insertion will not be allowed even if there are some vacant spaces at front. A circular queue uses the vacant space at front end as the rear space is occupied by some data. This ability allows a circular queue to add items even when an item occupies the rear end.A circular queue can be understood as First-In-First-Out(FIFO) data structure.

Representation of Circular Queue using Arrays:

Circular Queue data structure can be implemented using a one-dimensional array. We maintain two pointers FRONT and REAR to point to both ends. While adding items to a Queue, the Rear End of the Queue increases and while deleting items from the Queue the Front End increases.

Key Points:

 Initially both FRONT and REAR point to -1 which indicates that the queue is empty.

 If we add an element to the queue for the very first time, then FRONT and REAR point to 0.  Thereafter, each addition of item will increase the value of REAR, each deletion of item

increases the value of FRONT.

 When data items are added, the rear position of the queue increases upto LENGTH-1 of the queue and repeats the rear value from the lower bound value of the queue.

 When items are deleted, front end increases upto LENGTH-1 of the queue and repeats from the lower bound of the queue.

Operations:

Enqueue : Inserts an item into the queue Dequeue : Deletes an item from the queue Overflow Condition:

FRONT = (REAR+1) MOD LENGTH Underflow Condition:

FRONT = -1 or REAR = -1 Example:

(49)
(50)

C++ Program Code: #include<iostream.h> const int LENGTH=8; class Queue

{ private:

int cq[LENGTH], front, rear; public: Queue() { front=-1; rear=-1; }

int enqueue(int item) { if(front==(rear+1)%LENGTH) return 0; else { if(rear==LENGTH-1) rear=0; else rear++;

(51)

if(front<0) front=0; return 1; } } int dequeue() { if(front<0||rear<0) return 0; else {

cout<<"Item Deleted: "<<cq[front]; if(front==rear) front=rear=-1; else if(front=LENGTH-1) front=0; else front++; return 1; } } }; void main( ) { Queue q; int ch, data; int quit=0; while(!quit) { cout<<"\n---"; cout<<"\n CIRCULAR QUEUE "; cout<<"\n---"; cout<<"\n 1.ENQUEUE "; cout<<"\n 2.DEQUEUE "; cout<<"\n 3.EXIT "; cout<<"\n---"; cout<<"\nEnter Your Choice:"; cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(q.enqueue(data))

cout<<"Item Added into the Queue"; else

(52)

cout<<"Queue is Overflow...!"; break; case 2: if(!q.dequeue()) cout<<"Queue is Underflow...!"; break; case 3: quit=true; break; default: cout<<"Invalid Choice...!"; break; } } }

16. What is DEQueue? Explain how DEQueue is implemented using arrays Ans:

DEQueue is a kind of queue data structure which allows both addition and deletion of items on either sides of the queue. It allows both Rear and Front ends to add and delete items. That is why this data structure is called as ‘Double Ended Queue(DEQueue)’.

Representation of DEQueue:

DEQueue data structure can be represented using array data structure.

1. Initially both FRONT and REAR point to -1 which indicates that the DEQueue is empty.

2. In a DEQueue, when an item is added through Rear End for the very first time, then the item will be placed at Front end.

(53)

3. In a DEQueue, when an item is added through Front End for the very first time, then the item will be placed at Rear end.

While adding and deleting items to or from a DEQueue, we must specify through which end we are performing the task.

Operations:

addFromRear : Inserts an item into the DEQueue from Rear end. addFromFront : Inserts an item into the DEQueue from Front end.

deleteFromFront : Removes an element from the DEQueue from Front end. deleteFromRear : Removes an element from the DEQueue from Rear end.

(54)

Program:

#include<iostream.h> const int LENGTH=8; class DEQueue {

private:

int DQ[LENGTH]; int front, rear;

public:

DEQueue() { front=-1; rear=-1; }

int addFromRear(int item) { if(rear==LENGTH-1) return 0; else { rear++; DQ[rear]=item; if(front==-1) front=0; return 1;

(55)

}

int addFromFront(int item) { if(front==0) return 0; else { if(front==-1) front=rear=LENGTH-1; else front--; DQ[front]=item; return 1; } } int deleteFromFront() { if(front==-1||rear==-1) return 0; else {

cout<<"Item Deleted: "<<DQ[front]; if(front==rear) front=rear=-1; else front++; return 1; } } int deleteFromRear() { if(front==-1||rear==-1) return 0; else {

cout<<"Item Deleted: "<<DQ[rear]; if(front==rear) front=rear=-1; else rear--; return 1; } } }; void main( ) {

(56)

DEQueue q; int ch, data; int quit=0; while(!quit){ cout<<"\n---"; cout<<"\n DEQUEUE "; cout<<"\n---"; cout<<"\n 1. ADD FROM REAR "; cout<<"\n 2. ADD FROM FRONT "; cout<<"\n 3. DELETE FROM REAR "; cout<<"\n 4. DELETE FROM FRONT "; cout<<"\n 5. EXIT "; cout<<"\n---"; cout<<"Enter Your Choice:";

cin>>ch; switch(ch) { case 1: cout<<"Enter Data: "; cin>>data; if(q.addFromRear(data))

cout<<"Item Added into the Queue"; else cout<<"Queue is Overflow...!"; break; case 2: cout<<"Enter Data: "; cin>>data; if(q.addFromFront(data)) cout<<"Item Added into the Queue"; else cout<<"Queue is Overflow...!"; break; case 3: if(!q.deleteFromRear()) cout<<"Queue is Underflow...!"; break; case 4: if(!q.deleteFromFront()) cout<<"Queue is Underflow...!"; break; case 5: quit=1; break; default:

(57)

break; }

} }

17. What is Priority Queue? Explain how queue is implemented using arrays Ans:

Priority Queue is a kind of queue structure. Here, each item is assigned a value called ‘Priority’. Items can be inserted and deleted based on their priority value. An item can be inserted at any position of the queue according to its priority value. Priority queue does not follow the basic characteristic of regular queue called First-In-First-Out(FIFO).

We follow the following rules while we implement the Priority Queue. 1. An item of higher priority is processed before any element of lower priority.

2. Two items with same priority are processed according to the order in which they were added to the queue.

We can implement a Priority Queue using the technique called ‘Multi-Queue’ implementation. Here, we maintain multiple linear queues each assigned a unique priority value.

Representation of Priority Queue:

We can represent a priority queue using multiple linear queues each assigned a unique priority value. Items are inserted and deleted as per their priority value. Based on its priority value, the item will be added to an appropriate queue. An item will be added to the queue which is having the priority value as same as the item’s priority.

(58)

Program:

#include<iostream.h> int const NOP=3; int const MAXSIZE=5; class PriorityQueue { class CircularQueue { int CQueue[MAXSIZE]; int front,rear; public: CircularQueue() { front=-1; rear=-1; } int IsEmpty() {

(59)

return 1; else return 0; } int IsFull() { if((front==0&&rear==MAXSIZE-1)||(front==rear+1)) return 1; else return 0; } int Add(int x) { if(IsFull()) return 0; else { if(rear==MAXSIZE-1) rear=0; else rear++; CQueue[rear]=x; if(front<0) front=0; return 1; } }

int Delete(int &x) { if(IsEmpty()) return 0; else { x=CQueue[front]; if(front==MAXSIZE-1) front=0; else if(front==rear) front=rear=-1; else front++; return 1; } }

(60)

int First() { if(IsEmpty()) return 0; else return CQueue[front]; } int Last() { if(IsEmpty()) return 0; else return CQueue[rear]; } }; public: CircularQueue CQueue[NOP]; int AddItem(int,int);

int DeleteItem(int &); };

int PriorityQueue::AddItem(int d, int p) { if(p<1&&p>NOP) return 0; else return CQueue[p].Add(d); }

int PriorityQueue::DeleteItem(int &d) { int p=0; while(p<NOP&&(!CQueue[p].Delete(d))) p++; if(p>=NOP) return 0; return 1; } void main() { PriorityQueue pq; int d,ch,p,quit=0; do { cout<<"---"<<endl; cout<<" MENU "<<endl;

(61)

cout<<" 1. ADD "<<endl; cout<<" 2. DELETE "<<endl; cout<<" 3. EXIT "<<endl; cout<<"---"<<endl; cout<<"Enter Your Choice:"; cin>>ch;

switch(ch) {

case 1: cout<<"Enter Data and Priority:"; cin>>d>>p;

if(pq.AddItem(d,p))

cout<<"Item Added in "<<p<<" priority list"<<endl; else

cout<<"Addition Failed...!"<<endl; break;

case 2: if(pq.DeleteItem(d))

cout<<"Item deleted: "<<d<<endl; else

cout<<"Underflow...!"<<endl; break;

case 3: quit=1; break;

default: cout<<"Inavlid choice...!"<<endl; }

}while(!quit); }

18. What are the applications of Queue data structure? Explain them in brief Ans:

Queue data structures are widely used in computer science programming. Various techniques of Queue data structure such as Linear Queue, Circular Queue, Priority Queue etc. are used based on the requirements of the application.

The following are some of the applications of Queue data structure variants. 1. Simulation

2. CPU Scheduling in Multi-Programming Environment 3. Round Robin Algorithm

Simulation:

Simulation is the model of a real-life situation in the form of a computer program. It is to study the real-life situation under the control of various parameters. Based on the results of Simulation, the actual problem is solved.

Eg: Maintaining a Queue in a Ticket Counter Ticket

Counter

In the above example, a Linear Queue data structure can be used in which we follow First Come First Serve policy.

(62)

In Multi-Programming environment, a single CPU has to serve more than one program simultaneously. For example we have the following 3 jobs to be completed by the CPU.

1. Printing one document

2. Executing one System Interrupt 3. Playing one music file

If all the above jobs are entered into the task schedule of Operating System, then it categorizes those jobs by assigning them different priorities. Here Priority Queue can be used.

Round Robin Algorithm:

In Round Robin scheduling algorithm, CPU will serve the jobs based on the technique of time sharing. Suppose there are multiple processes like P1, P2, P3, . . . , Pn where each process requires different execution times. The arrival time of P1 is less than P2, P2 less than P3 then Pi less than Pi+1. The Round Robin algorithm takes a time slice or time quantum tand works for time t on each of the processes starting from P1 upto Pn. After reaching the last process i.e., Pn, it repeats the same order until all processes are served. Here Circular Queue can be used.

Eg:

Process Time Required

P1 7

P2 23

P3 9

P4 15

Let t=4, and the total time required is 7+22+9+15=54, the jobs are processed in the following order.

1. What is Tree? Explain its basic terminology Ans:

ATree is a non-linear data structure where the elements appear in a non-linear order. It is a collection of nodes connected by links/edges/branches. Tree data structure is the efficient means to maintain and manipulate data. It is used to represent data in hierarchical order. In a tree, a parent node can have any number of child nodes.

Example:

Terminology:

(63)

Child: The node that is immediate successor of a parent is the child to that parent.

Link: The pointer to a node. It connects two nodes in a tree. It is also called as Edge or Branch. Root:This is a specially designated node which has no parent. This is the very first node of the tree hierarchy.

Leaf:The node which is at the end and does not have any child is called leaf. It is also called as terminal node or external node.

Level: It is the rank in the hierarchy. The root node has level 0. If a node is at level L, then its child is at level L+1 and parent is at L-1.

Path:The series of nodes that are part of reaching a node from another node is called Path. Height:The maximum no.of nodes that is possible in a path starting from the root node to a leaf node is called the height of a tree. It is also called as depth of the tree.

Degree: The maximum no.of children that is possible for a node is known as the degree of a node.

Sibling: The nodes which have the same parent are called Siblings. There are totally 10 nodes in the tree.

Node A is the parent of B,C and D, B is the parent of E, F and G nodes The nodes B,C and D are children of A, H is the child of C.

Node ‘A’ is the root of the tree.

Nodes E, I, J, G, H and D are leaf/external nodes. Nodes B,C,F are internal nodes.

Level of A is 0, level of B,C and D is 1(level of A plus 1), level of E,F and G is 2(level of B plus 1).

Path of node I is A-B-F-I.

The height of the tree is 4. That is maximum level + 1. The degree of the node A is 3, B is 3, C is 1, D is 0 and F is 2. The degree of the tree is 3. That is maximum of all its node degree values.

The nodes B, C and D are siblings. A Tree is a finite set of one or more nodes such that:

1. There is a specially designated node called the root.

2. The remaining nodes are partitioned into n disjoint sets T1, T2, . . . , Tnwhere each Ti is a tree and they are called as subtrees of the root.

(64)

Ans:

A Binary Tree is a special form of a tree. Binary Tree data structure is used in various applications of computer science.

Like a general tree, a Binary Tree can also be designed as a finite set of nodes, such that: 1. T is empty, called empty Binary Tree.

or

2. T contains a specially designated node called the root of T, and the remaining nodes of T form two disjoint Binary trees T1 and T2 which are called the left tree and right

sub-tree. Example:

(65)

In a Binary tree, a node may have at most two children. There are two possible situations of a Binary tree.

1. Full Binary Tree 2. Complete Binary Tree Full Binary Tree:

A Full Binary Tree contains the maximum possible number of nodes at all levels. Complete Binary Tree:

A Binary tree is said to be a complete binary tree if all its levels, except the last level have the maximum number of possible nodes and all the nodes in the last level appear as far left as possible.

Properties of a Binary Tree:

1. In any Binary Tree, the maximum number of nodes on level ‘l’ is 2l. Proof:

The maximum no.of nodes on level l=0 is 20= 1

Similarly, l=1 is 21 = 2

l=2 is 22 = 4

l=3 is 23 = 8

2. The maximum number of nodes possible in a Binary Tree at height ‘h’ is 2h-1. Proof:

The maximum number of nodes is possible if each level contains maximum number of nodes.

If height h=1, then number of nodes possible is 2h-1, i.e., 21-1 = 2-1 = 1

If height h=2, then number of nodes possible is 2h-1, i.e., 22-1 = 4-1 = 3

If height h=3, then number of nodes possible is 2h-1, i.e., 23-1 = 8-1 = 7

If height h=4, then number of nodes possible is 2h-1, i.e., 24-1 = 16-1 = 15

3.The minimum number of nodes possible in a Binary Tree of height ‘h’ is ‘h’. Proof:

A Binary Tree contains minimum number of nodes if each level has the minimum number of nodes. So at each level there is only one node i.e., each parent node has one child node. Such trees are also called as ‘Skew Binary Tree’.

(66)

4. For a non-empty Binary Tree, if ‘n’ is the number of nodes and ‘e’ is the number of edges, then n=e+1.

Proof:

If number of nodes n = 1, then no.of edges e = 0 Similarly if n = 2 e = 1

if n = 3 e = 2

if n = 4 e = 3

Hence n = e+1 or e = n-1

5. The height of a Complete Binary Tree with ‘n’ number of nodes is Log2(n+1) . Proof:

Maximum number of nodes in a Binary Tree of height h is n=2h-1.

Hence n<=2h-1 or 2h>= n+1.

Therefore h = Log2(n+1) .

3. Explain how Binary Trees are implemented using Arrays. Ans:

There are two methods for representing Binary Tree data structure. 1. Array representation

2. Linked representation Array Representation:

We can represent the Binary Tree data structure using arrays, this representation is called linear or sequential representation. This type of representation is static, that is a block of memory for an array is allocated before storing the actual tree in it. Once the memory is allocated, the size of the tree is restricted.

In this method of representation, the nodes are stored level by level starting from the level 0(root node). The root node is stored in the first memory location as it is the first node of the tree.

Following rules can be used to decide the location of any node of a tree in the array. Note: Assume that the index starts from 1.

1. The root node is at location 1.

2. For any node with index i, where 1<i<=n

a. Parent(i) = i/2 for root node there is no parent. b. LChild(i) = 2*i if 2*i>n then i has no left child. c. RChild(i) = 2*i+1 if 2*i+1>n then i has no right child. Example:

(67)

 The minimum size of the array may require to store a Binary Tree with ‘n’ nodes is 2h-1.

 The maximum size of the array may require to store a Binary Tree with ‘n’ nodes is 2n-1.

Example:

To store a binary tree with 3 nodes.

Referências

Documentos relacionados

The Kwame Nkrumah Ideological Institute (1961-1966) was an ideological school for both the Ghanaian ruling party (Convention People’s Party) and the African freedom fighters

Independentemente do nível de detalhe do processo, a HUMINT contribui, de forma decisiva, para o CPI, através da recolha de dados/informação (fase dois) e os seus produtos contribuem

Para este fim tanto, a nível terrestre, são utilizados veículos motorizados de duas rodas (não abordados aqui) bem como alguns tipos de automóveis, desde carros ligeiros para

(B) Mean vital rates (6 SE) for each of the four defined groups of populations (central populations of the Northern and Southern species, and marginal populations of the Northern

As políticas de gestão florestal, uma vez que é uma fonte de matéria- prima inesgotável; o aperfeiçoamento do sistema de corte, resultando numa maior variedade de

(2017) examined the associations of smoking-related DNA methylation biomarkers and frailty in a population of older adults classified according to FI, and observed that

Utilizando os cenários dos filme “Fanny e Alexander” e “Gritos e Sussurros” (1972) e seus enredos, foi possível fazer uma análise sobre os contextos que

Conforme Rother (2007), os artigos de revisão narrativa são publicações amplas, apropriadas para descrever e discutir o desenvolvimento ou o &#34;estado da arte&#34; de