Вы находитесь на странице: 1из 23

Data Structures

SE E&TC
List of Practicals
1) Searching methods-Linear & Binary

2) Sorting Methods-Bubble, Selection & Insertion.

3) Data base Management using array of structure.

4) Polynomial addition using array of structure.

5) Implementation of singly linked list- Create, Insert, Delete, Search.

6) Implementation of stack using arrays & LL.

7) Queue using array & LL.

8) Evaluation of postfix expression (input will be postfix expression)

9) Operations on Binary search tree: Create, search, recursive traversals.

10) Implementation of Graph using adjacency Matrix.


Experiment No: 01

Title: Searching methods-Linear and Binary.

Aim of Experiment:
Write a menu driven program to perform following searching operations:
1) Linear search.
2) Binary search.

Objectives:
 After performing this experiment, student should be able to understand the
concept of a various Searching methods.
 Write functions for other simple searching methods like Fibonacci search.
Theory:
1) Binary search:
In its simplest form, binary search is used to quickly find a value in a sorted sequence
(consider a sequence an ordinary array for now). We'll call the sought value the target
value for clarity. Binary search maintains a contiguous subsequence of the starting
sequence where the target value is surely located. This is called the search space. The
search space is initially the entire sequence. At each step, the algorithm compares the
median value in the search space to the target value. Based on the comparison and
because the sequence is sorted, it can then eliminate half of the search space. By doing
this repeatedly, it will eventually be left with a search space consisting of a single
element, the target value.
For example, consider the following sequence of integers sorted in ascending order and
say we are looking for the number 55:
0 5 13 19 22 41 55 68 72 81 98

We are interested in the location of the target value in the sequence so we will represent
the search space as indices into the sequence. Initially, the search space contains indices
1 through 11. Since the search space is really an interval, it suffices to store just two
numbers, the low and high indices. As described above, we now choose the median
value, which is the value at index 6 (the midpoint between 1 and 11): this value is 41 and
it is smaller than the target value. From this we conclude not only that the element at
index 6 is not the target value, but also that no element at indices between 1 and 5 can
be the target value, because all elements at these indices are smaller than 41, which is
smaller than the target value. This brings the search space down to indices 7 through 11:
55 68 72 81 98
Proceeding in a similar fashion, we chop off the second half of the search space and are
left with:
55 68
Depending on how we choose the median of an even number of elements we will either
find 55 in the next step or chop off 68 to get a search space of only one element. Either
way, we conclude that the index where the target value is located is 7.
If the target value was not present in the sequence, binary search would empty the
search space entirely.
2) Linear search:
In computer science, linear search or sequential search is a method for finding a
particular value in a list , that consists in checking every one of its elements, one at a
time and in sequence, until the desired one is found.
For a list with n items, the best case is when the value is equal to the first element of the
list, in which case only 1 comparison is needed. The worst case is when the value is not
in the list (or occurs only once at the end of the list), in which case n comparisons are
needed.
Analysis of Linear Search:
The way in which big O is determined for a particular algorithm is algorithm analysis.
Take for example the simple linear search algorithm that we mentioned previously and
apply it to the value 3 and the ordered set .
Sequentially the algorithm would start from the index of the set, 0, and then look at each
next value until it finds the value 3, thus making four comparisons.

Army Institute of Technology-E&TC 2


But what about all of the other infinite number of integers that we could have looked
for? Let's try the value 6. The algorithm will first check 6 against 0, 1, 2, 3, 4, and 5 until
it halts without finding the value and thus makes six comparisons.
From this we can draw that the algorithm will make a number of comparisons equal to
the input size, n, and thus is .
Algorithm:
1. Binary Search:
Given A[N] is the Array of elements N, X is the number to be searched, lower contains
lower bound index and upper contains upper bound index of considered list. Variable mid
contains middle index of list in consideration.
1. [Initialize]
Lower=1
Upper=N
2. [Perform Search]
Repeat thru step 4 while lower<=Upper
3. [Obtain index of Midpoint of Interval]
Mid=(lower+upper)/2
4. [Compare]
If X< A[mid]
Then set upper to mid-1
Else If X>A[mid]
Then set lower to mid+1
Else Print ‘Successful Search’
Return(Mid)
5. [Unsuccessful Search]
Print ‘Unsuccessful Search’
Return(0)
2. Linear Search:
X is the number to be searched, A[N] is the Array of elements N, I is the index of array.
1. [Initialize Search]
I=1
A[N+1]=X
2. [Search Vector]
Repeat while A[I]!=X
I=I+1
3. [Successful Search?]
If I=N+1
Then Print ‘Unsuccessful Search’
Return(0)
Else Print ‘Successful Search’
Return (I).
Input:
Data in the form an array.
Output :
For each algorithm output should be in the form of:
Original List of numbers.
Number to be searched with its position.
Difference between binary and linear search:
Binary search runs in O(log n) time whereas linear search runs in O(n) times thus binary
search has better performance.
Program Listing
// Print out of programs
OUTPUT
// Print outs of program results
Applications:
1. Searching Telephone number of a particular person in Telephone book.
2. Finding information of a particular student in a large Student Database.
3. Simple Number Guessing game.
FAQ:
What is searching?
What is recursion?
References:
1. ‘C programming’ by Balguruswami.
2. ‘ Let us C’ Kanetkar.
3. ‘Fundamentals of data structures” sartaj sahani.

Army Institute of Technology-E&TC 3


Conclusion:

Army Institute of Technology-E&TC 4


Experiment No: 02

Title: Sorting Methods-Bubble, Selection &Insertion

Aim of Experiment:
Implement the following Sort Methods:
1. Bubble sort
2. Insertion sort
3. Selection sort.
Display results after every pass along with no. of comparisons and exchanges for already
sorted input and unsorted data.

Objective:
This assignment is designed to implement different sorting methods. Analyze the
given algorithms.

Theory:
1) Bubble sort:
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the
list to be sorted, comparing each pair of adjacent items and swapping them if they are in
the wrong order. The pass through the list is repeated until no swaps are needed, which
indicates that the list is sorted. The algorithm gets its name from the way smaller
elements "bubble" to the top of the list. Because it only uses comparisons to operate on
elements, it is a comparison sort.
Analysis of Bubble Sort:
Bubble sort has best-case complexity Ω (n). When a list is already sorted, bubble sort will
pass through the list once, and find that it does not need to swap any elements. Thus
bubble sort will make only n comparisons and determine that list is completely sorted. It
will also use considerably less time than О (n²) if the elements in the unsorted list are not
too far from their sorted places. The worst case complexity is O (n2).
Efficiency:
For each pass the number of elements scanned for comparisons reduces by 1.
Number of comparisons in the first pass =(n-1)
Number of comparisons in the Second pass =(n-2)
Number of comparisons in the last pass =1
Thus the total number of comparisons at the end of the algorithm would have been
(n-1) + (n-2) +(n-3)+…+2+1= n(n-1)/2 =n2 /2 +O(n) = O(n2)
Hence the order of the bubble sort algorithm is O(n2) in worst case
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to
greatest number using bubble sort algorithm. In each step, elements written in bold are
being compared.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
(14258)(14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458)(12458)
(12458)(12458)
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
(12458)(12458)
(12458)(12458)
(12458)(12458)
(12458)(12458)
Finally, the array is sorted, and the algorithm can terminate.

Army Institute of Technology-E&TC 5


2) Selection sort:
Selection sort works by selecting the smallest unsorted item remaining in the list, and
then swapping it with the item in the next position to be filled. The selection sort has a
complexity of O(n2).
Analysis of Selection Sort:
Selection sort is not difficult to analyze compared to other sorting algorithms since none
of the loops depend on the data in the array. Selecting the lowest element requires
scanning all n elements (this takes n − 1 comparisons) and then swapping it into the first
position. Finding the next lowest element requires scanning the remaining n − 1
elements and so on, for (n − 1) + (n − 2) + ... + 2 + 1 = n(n − 1) / 2 Θ(n2) comparisons.
Each of these scans requires one swap for n − 1 elements (the final element is already in
place).
The algorithm works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)
Here is an example of this sort algorithm sorting five elements:
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64
(nothing appears changed on this last line because the last 2 numbers were already in
order)
3) Insertion sort:
Every iteration of insertion sort removes an element from the input data, inserting it
into the correct position in the already-sorted list, until no input elements remain. The
choice of which element to remove from the input is arbitrary, and can be made using
almost any choice algorithm.
Sorting is typically done in-place. The resulting array after k iterations has the property
where the first k + 1 entries are sorted. In each iteration the first remaining entry of the
input is removed, inserted into the result at the correct position, thus extending the
result.
Analysis of Insertion Sort:
The best case input is an array that is already sorted. In this case insertion sort has a
linear running time (i.e., O(n)). During each iteration, the first remaining element of the
input is only compared with the right-most element of the sorted subsection of the array.
The worst case input is an array sorted in reverse order. In this case every iteration of
the inner loop will scan and shift the entire sorted subsection of the array before
inserting the next element. For this case insertion sort has a quadratic running time (i.e.,
O(n2)).
The average case is also quadratic, which makes insertion sort impractical for sorting
large arrays. However, insertion sort is one of the fastest algorithms for sorting arrays
containing fewer than ten elements.

Algorithm:
1. Bubble Sort:
Given array K of N elements, algorithm sorts the elements in
increasing(ascending) order. The variables Pass & Last denote pass counter &
position of last unsorted element respectively. I is index of array elements and
EXCHs is to count no of exchanges made by any pass.
1. (Initialize)
Last =N
2. (Loop)
Repeat through step 5 for Pass= 1,2,…N-1
3. (Initialize Exchanges counter for this Pass)
EXCHS=0
4. Repeat for I=1,2,….,Last-1
If K[I]>K[I+1]
Then swap (K[I] & K[I+1])
EXCHS=EXCHS+1
5. (Were any exchanges made on this pass?)
If EXCHS==0
Then Return // mission accomplished; return early

Army Institute of Technology-E&TC 6


Else Last=Last-1
6. (Finished)
Return //maximum number of passes required
2. Selection Sort:
Given array K of N elements, algorithm sorts the elements in
increasing(ascending) order. The variables PASS denotes pass counter &
MIN_INDEX denotes Position of smallest element in that pass. I is index of array
elements.
1. (Loop)
Repeat through step 4 for PASS=1,2,… N-1
2. (Initialize)
MIN_INDEX=1
3. (Obtain the element with smallest value)
Repeat for I= PASS+1,PASS+2,...,N
If K[I] <K[MIN_INDEX]
Then MIN_INDEX=I
4. (Exchange Elements)
If MIN_INDEX != PASS
Then swap K[PASS] & K[MIN_INDEX]
25. (Finished)
Return
3. Insertion Sort:
Given array K of N elements, algorithm sorts the elements in increasing
(ascending) order. The variables PASS denotes pass counter &
INDEX value at current pass. I is index of array elements.
1. (Loop)
Repeat through step 4 for PASS=1,2,… N-1
2. (Initialize)
INDEX=K[PASS]
J=PASS
3. (Obtain the element with smallest value)
Repeat if(J>0) && K[J-1]>INDEX
K[J] =K[J-1]
J=J-1
4. (Assign value at jth location)
K[J]=INDEX
5. (Finished)
Return
Input:
Data in the form an array.
Output:
For each algorithm output should be in the form of:
Original List of numbers.
Sorted list of numbers.
Program Listing:
/*Implement sorting methods - bubble sort, selection sort,insertion sort.*/
OUTPUT:
Application:
1) Useful in managing large amount of data.
2) Finding information of a particular student in a large Student Database.
3) Simple Number Guessing game.

FAQ:
What is sorting?
What is recursion?
What is difference between selection, insertion, and bubble sort methods?
What are the applications?

References:
1. ‘C programming’ by Balguruswami.
2. ‘ Let us C’ Kanetkar.
3. ‘Fundamentals of data structures” sartaj sahani.

Conclusion:

Army Institute of Technology-E&TC 7


Experiment No: 03
Title: Database Management using array of structure.
Aim of Experiment:
To create and manipulate database by using array of structure.
Objective :
 This assignment is designed to implement database of students by using array
of structure.
Description: This program creates database of student. This also displays students
information, search and updataes, delete and insert new.

Theory:
A constructed data type know as structure which is method for packing data of different
types is convenient tool for handling a group of logically related items. A structure is a
collection of data fields or variables of different types that is referenced under the same
name. It provides convenience means of keeping related information which are called
fields of members can be accessed and processed separately.
Defining a Structure
A structure type is usually defined near to the start of a file using a typedef statement.
typedef defines and names a new type, allowing its use throughout the program.
typedefs usually occur just after the #define and #include statements in a file.

Structure definition:
typedef struct student
{
int roll no;
char name[20];
int marks;
}student;
Here are examples of structure definition.
1) Without using typedef
struct Bankcust {
char name[15];
char address[20];
int balance;
int acno;
};
In this case the variables are declared as follows:
struct Bankcust cust;
2) Using typedef to have shorter name while declaring variables:
typedef struct {
char name[15];
char address[20];
int balance;
int acno;
} Bankcust;

This defines a new type cust variables of type Bankcust can be declared as follows.
Bankcust cust;
Notice how similar this is to declaring an int or float.
The variable name is cust, it has members called name, address, balance and acno.

Accessing Members of a Structure


Each member of a structure can be used just like a normal variable, but its name will be
a bit longer. To return to the examples above, member name of structure cust will
behave just like a normal array of char, however we refer to it by the name
cust.name
Here the dot is an operator which selects a member from a structure.
Where we have a pointer to a structure we could dereference the pointer and then use
dot as a member selector. This method is a little clumsy to type. Since selecting a
member from a structure pointer happens frequently, it has its own operator -> which
acts as follows. Assume that st_ptr is a pointer to a structure of type Bankcust We would
refer to the name member as
st_ptr -> name

Army Institute of Technology-E&TC 8


Arrays of Structures
To declare an array of a structures, we first define a structure and then declare an array
variable of that type. To declare an 100 element array of structures of type student
define earlier,
We write,
Struct Bankcust cust[100];
This creates 100 sets of variables that are organized as defined in the structure
Bankcust.
To access a specific structure, index the array name. For example, to print the name of
4th customer, we write
printf( “%s”, cust[3].name);
When you want to refer to a specific structure within an array of structures, index the
structure array name. When you want to index a specific element of a structure, index
the element. Thus, the following statement assigns ‘X’ to the first character of name in
the 3rd structure of cust.
cust[2].name[0]=’X’;

Algorithm:
1) Get no of students from user.
2) Store information of each student in database.
3) Display the student’s information.
4) Search student information.
5) Update.
6) Insert new student.
7) Delete student information.
Data structure and variables used:
Student structure is used to store student information like roll no, name and marks.
St[30] is array of structure used to store student info. of the class.
is used to store number of students.
I is used for loop to define index variable.
Input:
Add records to the student database
Select Operation to be performed.
Output :
Perform operations like add, search, modify, delete, display list, display record depending
on the operation selected and manipulate the database when required.
Application:
1) Used to store student information in college account section.
2) Used to store student information in college library section.
3) Used to represent the various databases.
Program Listing:
/*Program for Operations on a database */

OUTPUT:

FAQ:
What is structure?
What is database?
What are the different operations we perform on database?
References:
1. ‘C programming’ by Balguruswami.
2. ‘Fundamentals of datastructures” sartaj sahani.
Conclusion:

Army Institute of Technology-E&TC 9


Experiment No: 04

Title: Polynomial addition using array of structure

Aim of Experiment:
Write a program to implement polynomial addition using array of structure.

Objective:
i) To know algorithm for addition of two single variable polynomial.
ii) To implement algorithm.
iii) To display the resultant polynomial.

Theory:
A polynomial is either zero, or can be written as the sum of one or more non-zero terms.
The number of terms is finite. These terms consist of a constant (called the coefficient of
the term) multiplied by zero or more variables (which are usually represented by letters).
Each variable may have an exponent that is a non-negative integer (also known as a
natural number). The exponent on a variable in a term is equal to the degree of that
variable in that term. Since x = x1, the degree of a variable without a written exponent is
one. A term with no variables is called a constant term, or just a constant. The degree of
a constant term is 0. The coefficient of a term may be any number, including fractions,
irrational numbers, negative numbers, and complex numbers. We are stored the
polynomials i.e. coefficient and power by using structure variables. And add them and
result is displayed.
Structure definition for polynomial:
typedef struct poly
{ int coeff;
int expo;
}p;
p p1[10],p2[10],p3[10];
Algorithm:
1) Start
2) Take the total no of terms in polynomial i.e.t1,t2
3) Enter the coeff. and expo.in descending order.
4) Steps for addition of two polynomial:
i) Check the exponents of two polynomial for same,
If same then add the coefficients.
if(p1[i].expo==p2[j].expo)
p3[k].coeff=p1[i].coeff+p2[j].coeff;
and store result in to 3rd polynomial with the exponent == expo.of any term i.e.
p3[k].expo=p1[i].expo;
ii) If exponent of the term of 1st polynomial is greater than the 2nd then :
else if(p1[1].expo>p2[j].expo)
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
iii) Else exponent of the term of 2nd polynomial is greater than the 1st
then:
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
iv) If there is only 1st polynomial entered then
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
v) If there is only 2nd polynomial entered then
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
vi) Return the result to main function:
return(t3);
5) Stop.
Operations:
1) Read the choice from user.
2) Read 1st polynomial.
3) Read 2nd polynomial.
4) Perform addition.
5) Display result.

Army Institute of Technology-E&TC 10


Input:
Two polynomials i.e. coefficient and power of polynomials.
Output :
Addition of the polynomials.
Program Listing:
/* Polynomials addition using array of structures. */

OUTPUT:

References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion:

Army Institute of Technology-E&TC 11


Experiment No: 05
Title: Singly linked list
Aim of Experiment:
Write a menu driven program to perform following operations on singly linked list:
Create, Insert, Delete, Display, and Search.
Objectives:
After performing this experiment, student should be able to:
 Understand the concept of a singly linked list and various operations on it
 Write functions for other simple operations on such a linked list.
 Design a program for other variants of singly linked list that include use of a
pointer to last node, header node, circular linked list, and circular list with header
node.
Relevant Theory:
In computer science, a linked list is data structure that consists of a sequence of data
records such that in each record there is a field that contains a reference (i.e., a link) to
the next record in the sequence.

A linked list whose nodes contain two fields: an integer value and a link to the next node
Linked lists are among the simplest and most common data structures, and are used to
implement many important abstract data structures, such as stacks, queues, hash
tables, symbolic expressions, skip lists, and many more.
The principal benefit of a linked list over a conventional array is that the order of the
linked items may be different from the order that the data items are stored in memory or
on disk. For that reason, linked lists allow insertion and removal of nodes at any point in
the list, with a constant number of operations.
On the other hand, linked lists by themselves do not allow random access to the data, or
any form of efficient indexing. Thus, many basic operations — such as obtaining the last
node of the list, or finding a node that contains a given data, or locating the place where
a new node should be inserted — may require scanning most of the list elements.
Singly-linked list:
Linked list is a very important dynamic data structure. Basically, there are two types of
linked list, singly-linked list and doubly-linked list. In a singly-linked list every element
contains some data and a link to the next element, which allows to keep the structure.
On the other hand, every node in a doubly-linked list also contains a link to the
previous node. Linked list can be an underlying data structure to implement stack,
queue or sorted list.
Example
Sketchy, singly-linked list can be shown like this:

Each cell is called a node of a singly-linked list. First node is called head and it's a
dedicated node. By knowing it, we can access every other node in the list. Sometimes,
last node, called tail, is also stored in order to speed up add operation.
Singly-linked list. Internal representation:
Every node of a singly-linked list contains following information:
• A value (user's data);
• A link to the next element (auxiliary data).
Sketchy, it can be shown like this:

First node called head and no other node points to it. Link to the head is usually
stored it the class, which provides an interface to the resulting data structure. For
empty list, head is set to NULL.
Also, it makes sense to store a link to the last node, called tail.

Army Institute of Technology-E&TC 12


Though no node in the list can be accessed from the tail (because we can move
forward only), it can accelerate an add operation, when adding to the end of the list.
When list is big, it reduces add operation complexity essentially, while memory
overhead is insignificant. Below you can see another picture, which shows the whole
singly-linked list internal representation:

Algorithm:
Insertion in ordered list:
// x is the data element of the node to be inserted in linked list
// list is the starting node of the linked list
// next refers to the next node of the linked list
// info refers to info field of the node
Getnode (new)
Info (new) =x
next (new) =null
if list = null
list = new
else
begin
p=list
if x < info (p)
then next (new) = list
list = new
else
begin
while (next (p) <> null) and (x >= info (next (p))) do
p= next (p)

next (new)= next(p)


next (p) = new
end else //end of inner else
end else //end of outer else

Deleting from a linked list:


// current initially refers to first node of the linked list
// trail refers to one node previous to current
current = list
trail = null
while ( current <> null) and (info (current) <> x) do
begin
trail = current
current = next (current)
end/* end of the loop to search the node */
if current not null
then if trail = null
then
list = next (list) /* delete the first node */
else
next (trail) = next (current)
freenode (current)
else print (“node with the given value doesn’t exist in the list” )

Army Institute of Technology-E&TC 13


Search a node in a given linked list:
// current initially refers to the first node of the linked list
// next refers to the next node
count=0
while (current <> null) and info (current) <> x) do
current = next (current)
count = count +1
end // end of the loop

if (current = null)
call print(“ node with the given value doesn’t exist in the
list”)
else
display the position and the content of the node

Display the content of linked list:


// list is the starting node of the linked list
if (list = null)
call print(“ linked list is empty “)
else
while (current <> null ) do
call print( info(current))
current = next (current)
end //end of loop
end //end else
Input:
Input is the data/element that is to be added to the linked list as a new node.
Output:
Output is the data/elements present in the linked list.
Application :
To implement any kind of database. Manly used in manipulating data. Can be
used to store information like sparse matrix, polynomials, stack, queue.
Program Listing:
/*Operations on singly linked list - Create, Insert,Delete,Search */

OUTPUT:

FAQS :
o How it is useful in different application.
o What are the different ways to implement it.
o How to allocate dynamic memory.
References :
• “C programming “ Balguruswamy.
• ‘Fundamentals of datastructures” sartaj sahani.
• “Data structures “ Tananbom
Conclusion:

Army Institute of Technology-E&TC 14


Experiment No: 06
Title: Implementation of stack using arrays &linked list .
Aim of Experiment:
Implement stack, using array and linked list and perform operations like PUSH,
POP, and DISPLAY contents of the stack. Also display position of TOP.
Objective:
To know concept of STACK. This assignment will help the students to realize how
the different operation on stack like push, pop, display can be implemented.
Theory:
Stack:
A stack is an ordered collection of items into which items may be inserted and
deleted from one end called Top of stack. The stack is a LIFO i.e. element which is put in
the stack the last is the first to come out.
Static Implementation :
Since the stack is a ordered list of items we can implement stack using array. The
static implementation using array will have limitations on size of stack as array size has
to be predefined also the element is not physically deleted so that it does not release
memory allotted for the element which has to be removed.
If TOP==-1 it indicates stack is empty.
If TOP==MAX-1 it indicates stack is full.
We shall also define the new operation called ‘init’ due to which stack will initialise the
TOP to -1 to indicate an empty stack.
Dynamic implementation of stack:
Dynamic implementation of stack involves stack using Linked list.
In linked list:
i) There is no limitation of size, memory being only constraint.
ii) Element will be physically deleted thus releasing the memory allotted for the
element which has to be removed.]
iii) There is no leakage of memory.
iv) Since random access to any element is not required in a stack, the linked list
representation is preferred over the sequential organisation.
In this implementation the stack will be maintained as a singly linked list.
The first node will be pointed to by a pointer called ‘top’. Initially the stack is empty.
Hence there will be no list and top contain NULL. Whenever an element has to be
pushed, we will have to make a node to store the element and add this node to the
beginning of list. Top will always point to recently added node. When the pop operation
has to be performed, the first node will be deleted and the next node will become the
new TOP.
Algorithm:
Push(int item ,int S [])
// TOP as pointer which keep track of the top element in the stack.
// This algorithm gives push item in stack A
// Pre – S is stack
// Post – item is pushed in S stack
// Return –nothing
begin
if top>=n then
call stack_full()
return
end //if
top=top+1;
stack[top]=item;
end push;

Pop(int S [])
// TOP as pointer which keep track of the top element in the stack.
// This algorithm gives push item in stack A
// Pre – S is stack
// Post – item is poped in S stack
// Return –item which is top element of a stack.
begin
if top<= 0 then
call stack_empty()
return
end //if

Army Institute of Technology-E&TC 15


item=stack[top];
top=top-1;
return item;
end pop;

Stack_empty()
// TOP as pointer which keep track of the top element in the stack.
If (top == zero)
Call print(“stack is empty”);
End //if
End stack_empty;

Stack_full()
// TOP as pointer which keep track of the top element in the stack.
If (top == n)
Call print(“stack is full”);
End //if
End Stack_full;

void Stack_display (int S[])

Begin
counter =top
While counter >0
Call print(s[counter])
counter—
end //while
end Stack_display
Input:
Input is the data/number that is to be pushed on the stack.
Output:
Output is the data/element popped from the stack.
Applications :
• Expression conversion and evaluation
• Reversing a string
• Parsing
• Well formed Parenthesis.
• Decimal to binary conversion.
Program Listing:
/* stack in an array */

OUTPUT:

FAQs :
• How it is useful in different application.
• What are the different ways to implement it.
• What are the limitations of stack.
Conclusion:
Thus we have studied various operations like push, pop, display on stack.

Army Institute of Technology-E&TC 16


Experiment No: 07
Title: Queue using array and linked list.
Aim of Experiment:
Implement the queue using arrays and link list and perform operations like
INSERT, DELETE, DISPLAY, and finding FRONT & REAR elements.

Objective :
This assignment will help the student to realize the implementation difference
between stack and queue. Also this will clear the implementation concepts queue.
Theory:
The queue data structure is characterized by the fact that additions are made end, or
tail, of the queue while removals are made from the front, or head, of the queue. For this
reason, a Queue is referred to as a FIFO structure (First-In First-Out). Queues occur
naturally in situations where the rate at which clients’ demand for services can exceed
the rate at which these services can be supplied. For example, in network where many
computers share only a few printers, the print jobs may accumulate in print queue. In an
operating system with a GUI, applications and window communicate using messages,
which are placed in message queues until they can be handled.

Operations:
The main primitive operations of a queue are known as:
Add : adds a new node
Remove: removes a node

Additional primitives can be defined:


IsEmpty: reports whether the queue is empty
IsFull: reports whether the queue is full
Initialize: creates/initializes the queue
Destroy: deletes the contents of the queue (may be implemented by re-initializing
the queue)

Static implementation of queue:


The implementation of queue using sequential representation is done by using one
dimensional array called ‘q’ of some size MAX & two integer variable front and rear
initially front and rear is set to -1 whenever new element is to be added it is added from
rear & when element is removed it is removed from front.

Struct queue
{
Int q[MAX];
Int front,rear;
}
Dynamic implementation of queue:
Linked representation is used for dynamic implementation of queue,
In linked representation there is no memory constraint. size can be increased at run
time.
We can also release the memory when the element is removed from queue.
To create queue using Linked representation following steps are implemented:
1) Front and rear are NODE type pointer, which are NULL.
2) Whenever new node is created set rear to new.
3) Whenever node is to be deleted store address of front into temp and decrease
front and release the temp.
Struct node
{ int data;
Struct nide * link;
}
Input :
Input is the data/element that is to be added to the queue.

Output:
Output is the data/element removed from the queue, data elements in the queue.

Application :
• Job scheduling in compiler.
• Queue simulation.

Army Institute of Technology-E&TC 17


Program Listing:

OUTPUT:

FAQs :
o How it is useful in different application.
o What are the different ways to implement it.
o What are the limitations of Queue.

References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom

Conclusion:

Army Institute of Technology-E&TC 18


Experiment No: 08
Title: Evaluation of postfix expression

Aim of Experiment:
Take postfix expression as a input and evaluate it for result.

Objective :
This assignment will help the student to know how the postfix expression
evaluation.
Theory:
The expression a + b*(c - d )+ e written in postfix form is abcd - * + e +. This looks
rather cryptic. You can get the idea most easily if you read it backwards as `` add e to
(add (times (c - d) and b) to a)''. A few more examples are shown in Table which may
serve better than an elaborate explanation:
Table: Converting expressions to postfix
notation.
a+(b+c) abc++
(a+b)+c ab+c+
a-b*c abc*-
(a/b)*(c/d) ab/cd/*
a/(b+c*d-e) abcd*+e-/
a-b*c+d/e abc*-de/+

Algorithm:

Postfix Expression :

STEP 1 : Read the given postfix expression into a string called postfix.

STEP 2 : Read one character at a time & perform the following operations :
1. If the read character is an operand, then convert it to float and
push it onto the stack.
2. If the character is not an operand, then pop the operator from stack
And assign to OP2. Similarly, pop one more operator from stack
and assign to OP1.

3. Evaluate the result based on operator x.


4. Push the result (based on operator x) onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.
STEP 4 : Return the result from this procedure or algorithm and display the
result in main program.
In normal algebra we use the infix notation like a+b*c. The corresponding postfix
notation is abc*+. The algorithm for the evaluation of postfix ex. is as follows :
 Scan the Postfix string from left to right.
 Initialize an empty stack.
 If the scanned character is an operand, add it to the stack. If the scanned
character is an operator, there will be at least two operands in the stack.
o If the scanned character is an Operator, then we store the top most
element of the stack(topStack) in a variable temp. Pop the stack. Now
evaluate topStack(Operator)temp. Let the result of this operation be
retVal. Pop the stack and Push retVal into the stack.
o Repeat this step till all the characters are scanned.
 After all characters are scanned, we will have only one element in the stack.
Return topStack.
Input:
Input is the postfix expression which we want to evaluate.

Output:
Output is the result of postfix expression.

Army Institute of Technology-E&TC 19


Program Listing:

OUTPUT:

FAQs :
o How it is useful in different application.
o What are the different ways to implement it.
o What are the limitations of it.

References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom

Conclusion:

Army Institute of Technology-E&TC 20


Experiment No: 09 Title: Operations on binary search tree.
Aim of Experiment:
To write program to create a binary search tree and to perform primitive operations on
it.
Objective :
i) To implement logic for constructing binary search tree.
ii) To implement following primitive operations-
Create , search, recursive traversals .
Theory:
Tree:
Tree is a data structure in the form of a finite set of elements that is either empty or is
partitioned into one or more disjoint subsets of which one subset is special contains a
single element called as root of the tree. The two other subsets are themselves binary
trees called as children of root node. The root is not child of any node.
Binary Tree:
A binary tree is a finite set of nodes which is either empty or consists of root and two
disjoint binary trees called the left sub-tree and right sub-tree.

Binary search tree:


Binary search tree is binary tree which have all the values less than the root will lie in
left sub tree & having values greater than the root lie in right sub tree.

In computer science a binary search tree (BST) is a node based binary tree data structure
which has the following properties:

 The left sub-tree of a node contains only nodes with keys less than the node's
key.
 The right sub-tree of a node contains only nodes with keys greater than the
node's key.
 Both the left and right sub-trees must also be binary search trees

Traversal:
Traversal is a systematic way of retrieving information form tree in such a way that no
node will be left unvisited or no node will be visited twice or more.
There are different techniques of traversals:
1) Pre-order
2) Post-order
3) In-order
4) Depth first search
5) Breadth first
Each of these methods start processing from root of tree.

1) Pre-order: In this data on the root node will be printed first then we move on the
left sub-tree and go on printing the data till we reach to the leftmost node. Print the
data at that node and then move to the right sub-tree.

2) In-order : In this traversal first we go towards the leftmost node to print data on
that node then traversing left sub-tree then print root node then traverse right
subtree.

3) Post-order: In post order traversal we follow the LRD principle i.e. move to the
leftmost node check if right sub-tree is there or not if not then print the leftmost
node, if right sub tree is there move towards rightmost node.

Algorithm:
Algorithm for search:
Algorithm search (tree node,key)
1) If tree is empty
Return NULL.
2) If key = root of key
Return root.
3) Else If key<root of key
Return (search( root of left child, key))
4) Else
Return (search( root of right child, key))

Army Institute of Technology-E&TC 21


5) If key is not found
Return NULL
End search.

Algorithm for create :


Modify above search algorithms in such way that if key is found into BST return NULL
otherwise return last visited leaf node.
Algorithm create(tree node,key,data )
1) Tree ptr, temp;
Temp= search(tree node, key);
2) If temp= NULL return
3) Allocate memory for ptr
4) Ptr of key = key
Ptr of data =data
Ptr of left child =ptr of right child=NULL.
5) If tree is not empty
If key < temp of key
Temp of left child = ptr return tree node
Else temp of right child =ptr return tree node
Else node =ptr return ptr
End create.
Input:
Data in the form of numbers.

Output:
Output is the BST and primitive operations on BST.

Application:
• priority queues
• associative arrays
Program Listing:

OUTPUT:

FAQs :
o How it is useful in different application.
o What are the different ways to implement it.
o What are the limitations of BST.

References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom

Conclusion:

Army Institute of Technology-E&TC 22


Experiment No: 10
Title: Implementation of graph using adjacency matrix.
Aim of Experiment:
To write program to Implementation of graph using adjacency matrix.
Objective :
i) To implement logic for constructing graph using adjacency matrix.
ii) To implement following primitive operations-
Create, Insert, Search, Delete.
Theory:
Graph:
In computer science, a graph is an abstract data structure that is meant to implement
the graph concept from mathematics
A graph data structure consists mainly of a finite (and possibly mutable) set of ordered
pairs, called edges or arcs, of certain entities called nodes or vertices. As in mathematics,
an edge (x,y) is said to point or go from x to y. The nodes may be part of the graph
structure, or may be external entities represented by integer indices or references.
Formal Definition: A graph G can be defined as a pair (V,E), where V is a set of
vertices, and E is a set of edges between the vertices E ⊆ {(u,v) | u, v ∈ V}.

Adjacency matrix:
In mathematics and computer science, an adjacency matrix (or one-hop connectivity
matrix) is a means of representing which vertices of a graph are adjacent to which other
vertices. Another matrix representation for a graph is the incidence matrix Specifically,
the adjacency matrix of a finite graph G on n vertices is the n × n matrix where the
nondiagonal entry aij is the number of edges from vertex i to vertex j, and the diagonal
entry aii, depending on the convention, is either once or twice the number of edges
(loops) from vertex i to itself. Undirected graphs often use the former convention of
counting loops twice, whereas directed graphs typically use the latter convention. There
exists a unique adjacency matrix for each graph (up to permuting rows and columns),
and it is not the adjacency matrix of any other graph. In the special case of a finite
simple graph, the adjacency matrix is a (0,1)-matrix m with zeros on its diagonal. If the
graph is undirected, the adjacency matrix is symmetric.
Operations:
6) Create a graph.
7) Insert new node in created graph.
8) Delete node from the graph.
9) Search a node (DFS/BFS).

Input:
1) Adjacency matrix.
2) Enter the starting vertex for DFS/BFS.

Output:
Element Found by DFS/BFS.
Program Listing:

OUTPUT:

References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion:

Army Institute of Technology-E&TC 23

Вам также может понравиться