DS LAB MANUAL
DS LAB MANUAL
2021-22
1
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
CONTENTS
S.NO PROGRAMS Page
No.
1 Course Description 3
2 Lab Objectives 3
3 Lab Outcomes 4
4 Guide Lines to Students 5
5 Lab Requirements 5
6 Program-1: Write a Java program using the data structure arrays to 7
multiply two given matrices of same order.
7 Program-2: Develop a program in java to read a sparse matrix of integer 10
values in the 2D array format and convert the sparse matrix to <row,
column, value> format and search for an element specified by the user.
Print the result of the search appropriately.
8 Program-3: Write Java programs to implement the STACK ADT using 13
an array.
9 Program-4: Write Java programs to implement the QUEUE ADT using 17
an array.
10 Program-5: The compilers always convert infix expression into postfix 22
to perform further operations like parsing, lexical analysis etc. Select an
appropriate data structure and develop a program to convert an infix
expression into postfix using stack.
11 Program-6: Write Java programs to implement the STACK ADT using a 25
singly linked list.
12 Program -7: Evaluation of postfix expressions is done by compilers 29
during the compilation process. Design and Develop a program to evaluate
a postfix expression using stack.
13 Program -8: Write Java programs to implement the QUEUE ADT using 32
a singly linked list.
14 Program -9: Write a java program that determines whether parenthetic 36
symbols ( ), { } and [ ] are nested correctly in a string of characters (use
stack ADT).
15 Program -10: Write a java program that uses both stack and queue to 39
test whether the given string is a palindrome (Use Java Utility).
16 Program -11: Files are stored in memory in tree structure directory. 43
Design and develop a program to create a directory having files with
unique file-id in the hard disk and display the files in all three traversal
orders using Binary Search Tree (BST).
17 Program -12: Consider a class having 100 students where, the details of 48
each student like name, roll number and marks of 3 subjects is to be
stored. Design and develop a program to construct a singly linked list to
enter records of different students in list, display the list and calculate the
percentage of each student. Also count the number of students passed
(scored >40 in all the subjects).
Viva Voice
2
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
I. COURSE DESCRIPTION
OOP is widely accepted as being far more flexible than other computer
programming languages. OOPs use three basic concepts as the fundamentals for
the Abstraction, Polymorphism, Event Handling and Encapsulation are also
significant concepts within object oriented programming languages that are
explained in online tutorial describing the functionality of each concept in detail.
The java platform is undoubtedly fast moving and comprehensive. Its many
application programming interfaces (APIs) provide a wealth of functionality for all
aspects of application and system-level programming. Real-world developers
never use one or two APIs to solve a problem, but bring together key functionality
spanning a number of APIs, Knowing which APIs you need, which parts of which
APIs you need, and how the APIs work together to create the best solution can be
a daunting task.
3
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
CO1 Make use of Java Arrays to solve real world problems. 1 to 5,9,10,12 1
1 to 5,9,10,12
CO2 Develop a java program for implementing the linked list. 1,2
1 to 5,9,10,12 1,2
CO3 Build a real world application in Java using stacks and queues.
CO4 Apply the concepts of trees for solving real world problems. 1 to 5,9,10,12 1,2
1 to 5,9,10,12 1,2,3
CO5 Identify the most suitable data structure for real world application.
CO6 Experiment with all data structures in a high-level language for problem solving. 1 to 5,9,10,12 1,2,3
CO4 √
CO5 √
CO6 √
PO11
PO12
PSO1
PSO2
PSO3
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
CO#/
POs
CO1 3 2 2 3 3 3 3 3
2
3
CO2 3 2 3 3 3 3 3 3
2
3
CO3 3 1 2 3 3 3 3 3
1
3
CO4 3 1 3 3 2 3 3 3 3
3 3
CO5 3 3 3 3 1 3 3 3 3
4
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
3 3
CO6 3 3 3 3 2 3 3 3 3
1. Equipment in the lab for the use of student community. Students need to
maintain a proper decorum in the computer lab. Students must use the
equipment with care. Any damage is caused is punishable.
2. Students are supposed to occupy the systems allotted to them and are
not supposed to talk ormake noise in the lab.
3. Students are required to carry their observation book and lab records
with completed exerciseswhile entering the lab.
4. Lab records need to be submitted every week.
5. Students are not supposed to use pen drives in the lab.
V. LABREQUIREMENTS
Use eclipse or Netbean platform and acquaint with the various menus,
create a testproject, add a test class and run it see how you can use auto
suggestions, auto fill. Trycode formatter and code refactoring like
renaming variables, methods and classes. Trydebug step by step with a
small program of about 10 to 15 lines which contains at leastone if else
condition and a for loop.
Program:-
5
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Compile:
The command javacis used to compile the java code and it is used as shown
below. Make sure that the name of the java file must be same as the public class
name that contain the main() function.
D:>javac Prog_name.java
Run:
The command java is used to execute the java code in the Java Virtual Machine
and it is used as shown below:
D:>java Prog_name
6
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 1
Problem Statement
Write a Java program using the data structure arrays to multiply two given matrices of same
order.
Student Learning Outcomes
The students are able to develop an application using Array data structure.
Algorithm
The definition of matrix multiplication is that if C = AB for an n × m matrix A and an m × p
matrix B, then C is an n × p matrix with entries
From this, a simple algorithm can be constructed which loops over the indices i from 1 through n
and j from 1 through p, computing the above using a nested loop:
7
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Matrix()
{
mat = null;
row = col = 0;
}
Matrix(int order)
{
mat = new int[order][order];
row = col = order;
}
void readMat(Scanner read)
{
for(int r = 0; r < row; r++)
for(int c = 0; c < col; c++)
mat[r][c] = read.nextInt();
}
void printMat()
{
for(int r = 0; r < row; r++)
{
for(int c = 0; c < col; c++)
System.out.print(mat[r][c] + " ");
System.out.println();
}
}
Matrix matMultipy(Matrix m)
{
Matrix prod = new Matrix(this.row);
for(int i = 0; i <this.row; i++)
for (int j = 0; j <this.col; j++)
{
prod.mat[i][j] = 0;
for(int k = 0; k <this.row; k++)
prod.mat[i][j] = prod.mat[i][j] +
this.mat[i][k] * m.mat[k][j];
}
8
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
return prod;
}
}
Description of the Program
class Matrix
1. Matrix() – The constructor where row and column variables are initialised
2. Matrix(int order)- The constructor where row and column variables are assigned with
order of the matrix.
3. void readMat(Scanner read) – Function reads the matrix elements into two-dimensional
array mat[r][c].
4. void printMat()- Function prints the array elements in the matrix form.
5. Matrix matMultipy(Matrix m)- Performs the matrix multiplication according to the
algorithm.
Input Output
Matrix Multiplication of same order
Enter the order: 3
Enter the elements of 1st Matrix
4 5 3
9 2 1
1 2 4
Enter the elements of 2nd Matrix
6 4 2
1 3 5
7 8 9
1st Matrix
4 5 3
9 2 1
1 2 4
2nd Matrix
6 4 2
1 3 5
7 8 9
Product Matrix
50 55 60
63 50 37
36 42 48
9
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 2
Problem Statement
Develop a program in java to read a sparse matrixof integer values in the 2D array format and convert
the sparse matrix to <row, column, value> format and search for an element specified by the user. Print
the result of the search appropriately.
Student Learning Outcomes
The students are able to develop an application using Array data structure.
Algorithm
The sparse matrix or sparse array is a matrix in which most of the elements are zero.
Input number of rows, number of columns and accordingly the elements in the spare matrix[rw]
[cl] where rw-no. of rows, cl-no.of columns.
Let size=0, k=0, index=0.
Define result matrix as int resultMatrix[][] = new int[3][size]
For row from 0 to rw
o For column from 0 to cl
o If the spare matrix element is not equal to 0, then
Increment ‘size’
resultMatrix[0][k] = row;
resultMatrix[1][k] = column;
resultMatrix[2][k] = sparseMatrix[row][column];
Increment ‘k’.
Input ‘key’ element to be searched.
For index from 0 to size
o If resultMatrix[2][index] == key, then
Print the element found at (resultMatrix[0][index] , resultMatrix[1][index]
Program
package Experiment2;
import java.util.*;
public class SparceMatrixApp
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
10
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
int cl = read.nextInt();
int sparseMatrix[][] = new int[rw][cl];
11
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
if(flag == 0)
System.out.println("Element not found");
read.close();
}
}
Description of the Program
1. Read the number of rows and columns of the sparse matrix from the user
2. Read the Sparse Matrix elements entered by user in 2D array
3. The variable ‘size’ counts the total number of non-zero elements by checking every element in
the sparse matrix.
4. Define the result Matrix by int resultMatrix[][] = new int[3][size];
5. Generate and display the result matrix by following steps:
Check every element in the spare matrix which is not equal to 0.
If the element is non-zero, the corresponding row number, column number and the non-
zero element will be stored in the resultMatrix[][](row0, row1 and row2 of column0).
The next non-zero element of sparse matrix will be stored inresultMatrix[][](row0, row1
and row2 of column1) . This continues for all the non-zero elements.
7. Match the ‘key’ element with the resultMatrix[2][index] for the index from 0 to ‘size’
8. When the element is found, the corresponding row number from resultMatrix[0][index] and
column number from resultMatrix[1][index] has to be displayed.
Input Output
2D Array format for Sparse Matrix
Enter Number of Rows :5
Enter Number of Columns :6
Enter the Values of Matrix:
0 0 0 0 9 0
0 8 0 0 0 0
4 0 0 2 0 0
0 0 0 0 0 5
0 0 2 0 0 0
Triplet Representation :
Row: 0 1 2 2 3 4
Column:4 1 0 3 5 2
Value: 9 8 4 2 5 2
Enter an element to search in sparse matrix:2
Element found at (2,3)
Element found at (4,2)
12
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 3
Problem Statement
Write Java programs to implement the STACK ADT using an array.
Student Learning Outcomes
The students are able to develop an application using Stack data structure.
Algorithm
Input the size of the stack, choice of the stack operation
bool isfull()
if (top==MAXSIZE)return true
elsereturn false
endif
boolisempty()
if(top ==-1)returntrue;
elsereturnfalse;
endif
13
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
if stack is emptyreturnnull
endif
data ← stack[top]
top ← top -1
return data
end procedure
14
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
stack.printStack();
break;
case 4: flag = false;
break;
default: System.out.println("Inavlid Choice try
again...");
}
}
read.close();
}
}
class ArrayStack
{
int top;
int maxSize;
int a[];
ArrayStack(int size)
{
a = new int[size];
top = -1;
maxSize = size;
}
void printStack()
{
if(!isEmpty())
{
for(int i = top; i > -1; i--)
System.out.println(a[i]);
}
else
System.out.println("Stack is Empty");
}
boolean isEmpty()
{
return (top < 0);
}
boolean isFull()
{
return (top >= (maxSize-1));
}
boolean push(int x)
{
if (isFull())
return false;
else
{
a[++top] = x;
return true;
}
}
int pop()
{
if (isEmpty())
return -1;
else
15
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
return a[top--];
}
}
o Create a one dimensional array (int a[SIZE]) with size read from the user to store stack
elements.
o Define a integer variable 'top' and initialize with '-1'. (int top = -1) and MAXSIZE=SIZE
o printStack() - Prints the elements of a Stack according to the algorithm
o push(value) - Inserting value into the stack according to the algorithm
o pop() - Delete a value from the Stack according to the algorithm
Class ArrayStackApp
Input Output
Stack Implementation Using Array
Enter the size of the Stack: 2
1. Push element in stack
2. Pop an element from Stack
3. Display the Stack
4. Exit
Select your option: 1
Enter the element to push: 10
10 successfully pushed on stack
1. Push element in stack
2. Pop an element from Stack
3. Display the Stack
4. Exit
Select your option: 1
Enter the element to push: 20
20 successfully pushed on stack
1. Push element in stack
2. Pop an element from Stack
3. Display the Stack
4. Exit
Select your option: 1
Enter the element to push: 30
Stack Overflow
1. Push element in stack
2. Pop an element from Stack
3. Display the Stack
16
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
4. Exit
Select your option: 3
Stack contents
20
10
1. Push element in stack
2. Pop an element from Stack
3. Display the Stack
4. Exit
Select your option: 4
Program - 4
Problem Statement
Write Java programs to implement the QUEUE ADT using an array.
Student Learning Outcomes
The students are able to develop an application using Queue data structure.
Algorithm
Input the size of the queue, choice of the queue operation
1. Enqueue element in stack
2. Dequeue an element from Stack
3. Display the queue
4. Exit
bool isfull()
if rear == MAXSIZE – 1 return true;
else return false;
endif
bool isempty()
if front < 0 or front > rear return true;
else return false;
endif
procedure enqueue(data)
if queue is full return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
procedure dequeue
if queue is empty return underflow
end if
data = queue[front]
front ← front + 1
17
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
return true
end procedure
procedure printQueue(data)
if queue is not Empty
for i= front to rear
return data
else
return false
endif
end procedure
Program
package Experiment4;
import java.util.*;
public class ArrayQueueApp
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
boolean flag = true;
System.out.println("Queue Implementation Using Array");
System.out.print("Enter the size of the Queue: ");
int size = read.nextInt();
ArrayQueue queue = new ArrayQueue(size);
while(flag)
{
System.out.println("1. Add an element in to queue");
System.out.println("2. Remove an element from queue");
Sy
stem.out.println("3. Display the queue");
System.out.println("4. Exit");
System.out.print("Select your option: ");
int ch = read.nextInt();
switch(ch)
{
case 1: System.out.print("Enter the element to add:
");
int ele = read.nextInt();
if (queue.enqueue(ele))
System.out.println(ele + "
successfully added to queue");
else
System.out.println("Queue Overflow");
break;
case 2: ele = queue.dequeue();
if(ele == -1)
System.out.println("Queue Underflow");
else
System.out.println(ele + " dequeued
from queue");
break;
case 3: System.out.println("Queue contents");
queue.printQueue();
break;
case 4: flag = false;
18
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
break;
default: System.out.println("Inavlid Choice try
again...");
}
}
read.close();
}
}
//Class for queue
class ArrayQueue
{
private int arr[]; // array to store queue elements
private int front; // front points to front element in
the queue (if any)
private int rear; // rear points to last element in the
queue
private int capacity; // maximum capacity of the queue
private int count; // current size of the queue
19
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
class ArrayQueueApp
20
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
If any other option is given then print “Invalid Choice try again...”
Input Output
Queue Implementation Using Array
Enter the size of the Queue: 2
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 1
Enter the element to add: 10
10 successfully added to queue
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 1
Enter the element to add: 20
20 successfully added to queue
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 1
Enter the element to add: 30
Queue Overflow
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 3
Queue contents
10 20
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 2
10 dequeued from queue
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 2
20 dequeued from queue
1. Add an element in to queue
2. Remove an element from queue
3. Display the queue
4. Exit
Select your option: 4
21
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program - 5
Problem Statement
The compilers always convert infix expression into postfix to perform further operations like
parsing, lexical analysis etc. Select an appropriate data structure and develop a program to
convert an infix expression into postfix using stack.
Student Learning Outcomes
The students are able to develop an application using Stack data structure.
Algorithm
Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression Y.
Program
package Experiment5;
import java.util.Scanner;
public class InfixToPostfixApp
{
22
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
23
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
}
}
class Stack
{
char a[] = new char[100];
int maxSize = 50;
int top = -1;
boolean isFull()
{
return (top >= (maxSize-1));
}
void push(char c)
{
if (isFull())
{
System.out.println("Stack full , no room to push , size=50");
System.exit(0);
}
else
a[++top] = c;
}
char pop()
{
return a[top--];
}
boolean isEmpty()
{
return (top == -1) ? true : false;
}
char peek()
{
return a[top];
}
}
Description of the Program
class InfixToPostfixApp
o The operator precedence is checked by using the function prec(char x). x is the
operator. If x = '*' or x = '/' or x = '%' have higher precedence. If x = '+' or x = '-' have
lower precedence.
o Pop the operator which has higher precedence first and add it to the postfix string.
24
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Peek() - Method in Java is used to retrieve or fetch the first element of the Stack or the
element present at the top of the Stack. The element retrieved does not get deleted or removed
from the Stack.
class Stack – performs push and pop operation of the operators on to the stack
Input Output
Program - 6
Problem Statement
Write Java programs to implement the STACK ADT using a singly linked list.
Student Learning Outcomes
The students are able to develop an application using Stack data structure.
Algorithm
Input the choice of the stack operation
procedure push(data)
Define a newNode with given value.
set newNode → next = top.
set top = newNode.
Return top is not equal to null
End procedure
bool isEmpty
return when top == null
end
procedure pop()
define ele = -1
if stack is Empty
return -1;
else if top not equal to null
set ele = top.data
set top = top.next
else
25
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
procedure printStack(data)
Assign Node n=top
While n until not equal to null
Print n.data
Set n = n.next
End while
End procedure
Program
package Experiment6;
import java.util.*;
public class LinkedStackApp
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Linked List Stack");
LinkedListStack stack = new LinkedListStack();
boolean flag = true;
while(flag)
{
System.out.println("1. Push element in stack");
System.out.println("2. Pop an element from stack");
System.out.println("3. Display the stack");
System.out.println("4. Exit");
System.out.print("Select your option: ");
int ch = read.nextInt();
switch(ch)
{
case 1: System.out.print("Enter the element to push:
");
int ele = read.nextInt();
if (stack.push(ele))
System.out.println(ele + "
successfully pushed on stack");
else
System.out.println("Stack Overflow");
break;
case 2: ele = stack.pop();
if(ele == -1)
System.out.println("Stack Underflow");
else
System.out.println(ele + " popped out
of the stack");
break;
case 3: System.out.println("Stack contents");
stack.printStack();
break;
26
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Node(int d)
{
data = d;
next = null;
}
}
void printStack()
{
Node n = top;
while (n != null)
{
System.out.println(n.data);
n = n.next;
}
}
boolean push(int data)
{
Node node = new Node(data);
node.next = top;
top = node;
return (top != null);
}
boolean isEmpty()
{
return (top == null);
}
int pop()
{
int ele = -1;
if(isEmpty())
return -1;
else if(top != null)
{
ele = top.data;
top = top.next;
}
else
top = null;
27
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
return ele;
}
}
Description of the Program
class LinkedListStack
Class LinkedStackApp
Read the option from the user 1.Push 2.Pop 3.Display 4.Exit
Using Switch case,
o Case 1: To push the element if the stack is not full. If it is full then print “Stack
overflow”
o Case 2:To pop the element if the stack is not empty. If it is empty then print “stack
underflow”
o Case 3:Print the contents of the stack.
o Case 4:Exit.
If any other option is given then print “Invalid Choice try again...”
Input Output
Linked List Stack
1. Push element in stack
2. Pop an element from stack
3. Display the stack
4. Exit
Select your option: 1
Enter the element to push: 10
10 successfully pushed on stack
1. Push element in stack
2. Pop an element from stack
3. Display the stack
4. Exit
Select your option: 1
Enter the element to push: 20
20 successfully pushed on stack
1. Push element in stack
2. Pop an element from stack
3. Display the stack
4. Exit
Select your option: 3
Stack contents
20
10
1. Push element in stack
2. Pop an element from stack
3. Display the stack
4. Exit
Select your option: 2
20 popped out of the stack
1. Push element in stack
2. Pop an element from stack
28
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
29
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 7
Problem Statement
Evaluation of postfix expressions is done by compilers during the compilation process. Design
and Develop a program to evaluate a postfix expression using stack.
Student Learning Outcomes
The students are able to develop an application using Stack data structure.
Algorithm
Read postfix expression Left to Right from the user.
If operand is encountered,
o push it onto Stack
End If
o Evaluate B operator A
END
Program
package Experiment7;
import java.util.*;
public class PostfixEvalApp
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.print("\nEnter the expression in postfix: ");
String exp = read.nextLine();
System.out.println("Result = " + evaluatePostfix(exp));
read.close();
}
static int evaluatePostfix(String exp)
{
Stack stack = new Stack();
for(int i = 0; i <exp.length(); i++)
{
char c = exp.charAt(i);
if(Character.isSpaceChar(c))
continue;
else if(Character.isAlphabetic(c))
{
System.out.print("\nExpression should conatin only digits");
System.exit(0);
}
else if(Character.isDigit(c))
{
30
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
int n = 0;
while(Character.isDigit(c))
{
n = n * 10 + (int)(c - '0');
i++;
c = exp.charAt(i);
}
i--;
stack.push(n);
}
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch(c)
{
case '+': stack.push(val2+val1);
break;
case '-': stack.push(val2- val1);
break;
case '/': stack.push(val2/val1);
break;
case '*': stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
}
class Stack
{
Node top; // head of list
Stack() { top = null;}
Node(int d)
{
data = d;
next = null;
}
}
void push(int data)
{
Node node = new Node(data);
node.next = top;
top = node;
}
boolean isEmpty()
{
return (top == null);
}
int pop()
31
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
{
int ele = -1;
if(isEmpty())
return -1;
else if(top != null)
{
ele = top.data;
top = top.next;
}
else
top = null;
return ele;
}
int peek()
{
return top.data;
}
}
Description of the Program
evaluatePostfix(String exp)
o Pop two items say val1 and val2 from the stack
Result = 3300
32
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program - 8
Problem Statement
Write Java programs to implement the QUEUE ADT using a singly linked list.
Student Learning Outcomes
The students are able to develop an application using Linked List data structure.
Algorithm
Input the choice of the stack operation
procedure printStack(data)
Assign Node n=front
While n until not equal to null
Print n.data
Set n = n.next
33
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
End while
End procedure
Program
package Experiment8;
import java.util.*;
public class LinkedQueueApp
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Linked List Queue");
LinkedListQueue queue = new LinkedListQueue();
boolean flag = true;
while(flag)
{
System.out.println("1. Add an element in to queue");
System.out.println("2. Remove an element from queue");
System.out.println("3. Display the queue");
System.out.println("4. Exit");
System.out.print("Select your option: ");
int ch = read.nextInt();
switch(ch)
{
case 1: System.out.print("Enter the element to add:
");
int ele = read.nextInt();
if (queue.enqueue(ele))
System.out.println(ele + "
successfully added to the queue");
else
System.out.println("Queue Overflow");
break;
case 2: ele = queue.dequeue();
if(ele == -1)
System.out.println("Queue Underflow");
else
System.out.println(ele + " removed out
of queue");
break;
case 3: System.out.println("Queue contents");
queue.printQueue();
break;
case 4: flag = false;
break;
default: System.out.println("Inavlid Choice try
again...");
}
}
read.close();
}
}
class LinkedListQueue
{
34
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
35
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
36
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 9
Problem Statement
Write a java program that determines whether parenthetic symbols ( ), { } and [ ] are nested
correctly in a string of characters (use stack ADT).
Student Learning Outcomes
The students are able to develop an application using Stack data structure.
Algorithm
procedure checkbalance
Input the string with parenthesis [ ], { }, or ( )
Declare a character stack.
Now traverse the expression string str.
For i=0 to length of str
1. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it
to stack.
2. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from
stack and if the popped character is the matching starting bracket then
fine else parenthesis are not balanced.
After complete traversal, if there is some starting bracket left in stack then “not
balanced” otherwise “balanced”
End procedure
Program
package Experiment9;
import java.util.*;
public class BracketTestApp
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Enter string with parenthesis [],{},or( )");
String str = read.nextLine();
if (str.isEmpty())
System.out.println("Empty String");
else
System.out.println(checkBalance(str));
read.close();
}
public static String checkBalance(String str)
{
Stack stack = new Stack();
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
37
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
38
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
{
return top == 0 ? true : false;
}
int getStackSize()
{
return top;
}
private void increaseSize()
{
Object[] temp = new Object[size];
size = size * 2;
for (int i = 0; i < top; i++)
temp[i] = this.data[i];
this.data = new Object[this.size];
for (int i = 0; i < top; i++)
this.data[i] = temp[i];
}
}
Description of the Program
checkBalance(String str)
Define a new stack
For I=0 to length of the string
Scan the scan the string using char ch = str.charAt(i)
If ch is ']' or '}' or ')', check for the corresponding opening bracket. If it is there then pop
both opening and closing parenthesis.
If the stack is empty after complete traversal, then print “Balanced Parenthesis” otherwise
print “Not Balanced”
class Stack
BracketTestApp
Read the input string with parenthesis [ ], { }, or ( ).
Checks whether the string is empty. If it empty, then print “Empty String”.
Else call the checkBalance function which will return whether the parenthesis is balanced
or not.
Input Output
Enter string with parenthesis [ ], { }, or ( )
Jingle (bell) [hello] {[(gone with the wind)])
Not Balanced
Enter string with parenthesis [ ], { }, or ( )
Jingle (bell) [hello] {[(gone with the wind)]}
Balanced Parenthesis
39
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 10
Problem Statement
Write a java program that uses both stack and queue to test whether the given string is a
palindrome (Use Java Utility).
Student Learning Outcomes
The students are able to develop an application using Stack and Queue data structure.
Algorithm
Input the string and enter the choice
40
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program
package Experiment10;
import java.util.*;
public class PalindromeApp
{
public static void main(String[] args)
{
System.out.println("String Palindrome Test");
Scanner in=new Scanner(System.in);
System.out.print("Enter any string: ");
String inputString = in.nextLine();
System.out.println("a. Check palindrome using stack");
System.out.println("b. Check palindrome using queue");
System.out.print("Enter choice: ");
String ch = in.nextLine();
switch(ch.charAt(0))
{
case 'a':
case 'A': if(usingStack(inputString))
System.out.println("The input String "
+ inputString + " is a palindrome.");
else
System.out.println("The input String " +
inputString + " is not a palindrome.");
break;
case 'b':
case 'B': if(usingQueue(inputString))
System.out.println("The input String "
+ inputString + " is a palindrome.");
else
System.out.println("The input String "
+ inputString + " is not a palindrome.");
break;
default: System.out.println("Invalid Choice enter the
character! (TRY AGAIN)");
break;
}
in.close();
}
static boolean usingStack(String string)
{
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i <string.length(); i++)
stack.push(string.charAt(i));
String reverseString = "";
while (!stack.isEmpty())
reverseString = reverseString + stack.pop();
if (string.equals(reverseString))
return true;
else
return false;
}
static boolean usingQueue(String string)
{
41
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
42
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
43
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 11
Problem Statement
Files are stored in memory in tree structure directory. Design and develop a program to create a
directory having files with unique file-id in the hard disk and display the files in all three traversal
orders using Binary Search Tree (BST).
Student Learning Outcomes
The students are able to develop an application using Tree data structure.
Algorithm
Algorithm to implement Preorder
Program
44
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
package Experiment11;
import java.util.*;
public class BSTApp {
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
boolean b = true;
BST btree = new BST();
while (b)
{
System.out.println("1. Create Files \n2. Traverse \n3.
Exit");
System.out.print("Enter Choice: ");
int choice = read.nextInt();
switch(choice)
{
case 1: System.out.println("File Creation:");
System.out.print("Enter file
name: ");
read.nextLine();
String str = read.nextLine();
btree.insert(str);
break;
case 2: System.out.print("Traversal of file
structure in:");
System.out.println("Inorder,
Preorder and Postorder");
System.out.println("Inorder:-");
btree.inorder(btree.getRoot());
System.out.println("Preorder:-");
btree.preorder(btree.getRoot());
System.out.println("Postorder:-");
btree.postorder(btree.getRoot());
break;
case 3: b = false;
break;
default: System.out.println("Invalid choice try
again:");
}
}
read.close();
}
}
class File
{
static final Random gen = new Random();
static int c = 0;
static int [] random;
private String fname;
private int fID;
{
random = randomNumbers(50, 100);
}
45
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
File(String n)
{
fname = new String(n);
fID = random[c++];
}
static int[] randomNumbers(int n, int maxRange)
{
int[] result = new int[n];
Set<Integer> used = new HashSet<Integer>();
for (int i = 0; i < n; i++)
{
int newRandom;
do
{
newRandom = gen.nextInt(maxRange+1);
} while (used.contains(newRandom));
result[i] = newRandom;
used.add(newRandom);
}
return result;
}
int id()
{
return fID;
}
public String toString()
{
return String.format("File ID -> " + fID + "\tFile name -> "
+ fname);
}
}
class BST
{
private class Node
{
File data;
Node left;
Node right;
Node(File file)
{
data = file;
left = right = null;
}
}
private Node root;
private Node insert(File x, Node t)
{
if(t == null)
t = new Node(x);
else if(x.id() < t.data.id())
t.left = insert(x, t.left);
else if(x.id() > t.data.id())
t.right = insert(x, t.right);
return t;
}
46
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
void insert(String x)
{
File f = new File(x);
root = insert(f, root);
}
void inorder(Node t)
{
if(t == null)
return;
inorder(t.left);
System.out.println(t.data + " ");
inorder(t.right);
}
void preorder(Node t)
{
if(t == null)
return;
System.out.println(t.data + " ");
preorder(t.left);
preorder(t.right);
}
void postorder(Node t)
{
if(t == null)
return;
postorder(t.left);
postorder(t.right);
System.out.println(t.data + " ");
}
BST()
{
root = null;
}
Node getRoot()
{
return root;
}
}
Description of the Program
The class BST is used to create a binary search tree.
The class File is used to create files with random file ID.
The insert function insert the file into proper location based on the fileID.
The postorder traversal function traverse the fileIDs in post order traversal till the root is null.
The preorder traversal function traverse the fileIDs in pre order traversal till the root is null.
The inorder traversal function traverse the fileIDs in In order traversal till the root is null.
Input Output
1. Create Files
2. Traverse
3. Exit
Enter Choice: 1
File Creation:
Enter file name: Alpha
1. Create Files
2. Traverse
3. Exit
Enter Choice: 1
47
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
File Creation:
Enter file name: Beta
1. Create Files
2. Traverse
3. Exit
Enter Choice: 1
File Creation:
Enter file name: Gamma
1. Create Files
2. Traverse
3. Exit
Enter Choice: 1
File Creation:
Enter file name: Delta
1. Create Files
2. Traverse
3. Exit
Enter Choice: 1
File Creation:
Enter file name: Zeta
1. Create Files
2. Traverse
3. Exit
Enter Choice: 2
Traversal of file structure in:Inorder, Preorder and Postorder
Inorder:-
File ID -> 32 File name -> Delta
File ID -> 58 File name -> Beta
File ID -> 63 File name -> Gamma
File ID -> 76 File name -> Alpha
File ID -> 80 File name -> Zeta
Preorder:-
File ID -> 76 File name -> Alpha
File ID -> 58 File name -> Beta
File ID -> 32 File name -> Delta
File ID -> 63 File name -> Gamma
File ID -> 80 File name -> Zeta
Postorder:-
File ID -> 32 File name -> Delta
File ID -> 63 File name -> Gamma
File ID -> 58 File name -> Beta
File ID -> 80 File name -> Zeta
File ID -> 76 File name -> Alpha
1. Create Files
2. Traverse
3. Exit
Enter Choice: 3
48
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Program – 12
Problem Statement
Consider a class having 100 students where, the details of each student like name, roll number
and marks of 3 subjects is to be stored. Design and develop a program to construct a singly
linked list to enter records of different students in list, display the list and calculate the percentage
of each student. Also count the number of students passed (scored >40 in all the subjects).
Student Learning Outcomes
The students are able to develop an application using Linked List data structure.
Algorithm
Algorithm of creation of a Linked List
CREATE---In this algorithm a Linked List of nodes is created. The list is pointed by pointer first,
the last node of the list points to NULL., indicating the end of the list. Each node is having two
parts DATA and NEXT. Let us assume that a linked list of N number of nodes is to be created.
The operator new will be used for the dynamic allocation of node. A variable I is being used as a
counter to count the number of nodes in the created list.
STEPS:
1.first=new node;{create the 1st node of the list pointed by first};
2.Read(Data(first));
3.NEXT(First)=NULL;
4.Far a First; [point Far to the First]
5. For I=1 to N-1 repeat steps 6 to 10
6.X=new node;
7.Read(Data(X))
8.NEXT(X)=NULL;
9.NEXT(Far)=X; {connect the nodes}
10.Far=X;[shift the pointer to the last node of the list]
[end of For Loop]
11.END
TRAVERSING A LINKED LIST
Many a times, it is required to traverse whole of a linked list. For Example counting of nodes in a
list, printing data of all the nodes etc.TRAVEL: In this algorithm a linked list, pointed by first, is
traversed. The number of nodes in the list is also counted during the traverse. A pointer ptr is
being used to visit the various nodes in the list. A variable count is used to keep track of the
number of nodes visited during the traverse. The traverse stops when a NULL is encountered.
STEPS:
1.If First=NULL then {print “List empty” STOP};
2.count=0;
3.ptr=First; {point ptr to the 1st node}
4.While ptr<> NULL repeat Steps 5 to 6
5.count=count+1;
6.ptr=NEXT(ptr) [shift ptr to the next node]
7.print (‘Number of nodes=’, count)
8.END
In the above algorithm , step 6 is worth noting i.eptr=NEXT(ptr). This step means that the pointer
Ptr should be shifted to the node which is being pointed by NEXT(ptr);
SEARCHING A LINKED LIST
Search is an operation in which an item is searched in a linked list. This operation is similar to
traveling the list. An algorithm for search operation is given below:
SEARCH:
In this algorithm a linked list, pointed by first, is traversed. While traversing the data part of each
49
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
vivited node is compared with an item ‘x’. If the item is found then the search stops otherwise the
process continues til the end of the list(i.e NULL) is encountered. A pointer ptr is being used to
visit the various nodes in the list.
STEPS:
1.If first=NULL then{
Print “List empty”; STOP;}
2.ptr=First; [point ptr to the 1st node]
3.while (ptr<>NULL) repeat steps 4 to 5
4.If (DATA (ptr)= ‘X’)
Then {print “item found”;
STOP
}
5.ptr=NEXT (ptr); [shift ptr to the next node]
[end of while]
6.Print “item not found”;
7.END
It may be noted in the above algorithm that if the item ‘X’ is found then the search stops.
INSERTION.......
In this algorithm a node X is inserted at the beginning of a linked list. The Linked List is being
pointed by a pointer First at the beginning.
STEPS:
1.X=new node;
2.Read(DATA(X);
3.If (FIRST=NULL) then
{
First=X;
NEXT(X)=NULL;
}
Else
{
NEXT(X)=First;
First=X;
}
4.END
Program
package Experiment12;
import java.util.Scanner;
public class StudentApp
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Student Data entry");
System.out.print("Enter the number of records: ");
int n = sc.nextInt();
Student data;
for(int i = 0; i < n; i++)
{
data = new Student(sc);
list.create(data);
}
50
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Node(Student d)
{
data = d;
next = null;
51
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
}
public String toString()
{
return data.toString();
}
}
public void printList()
{
Node n = head;
while (n != null)
{
System.out.println(n);
n = n.next;
}
}
void create(Student data)
{
Node node = new Node(data);
/* If the Linked List is empty, then make the new node as head
*/
if (head == null)
{
head = node;
return;
}
/* traverse till the last node */
Node last = head;
while (last.next != null)
last = last.next;
/* Change the next of last node */
last.next = node;
return;
}
int traverse()
{
Node iter = head;
int count = 0;
while(iter != null)
{
if(iter.data.greater40()) count++;
iter = iter.next;
}
return count;
}
}
52
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Input Output
Student Data entry
Enter the number of records: 2
Enter student details
Name: Rajan
Roll Number: 1
Marks in subject-1: 60
Marks in subject-2: 30
Marks in subject-3: 45
Enter student details
Name: Ram
Roll Number: 2
Marks in subject-1: 60
Marks in subject-2: 70
Marks in subject-3: 75
The Student Details are:
Name :Rajan
Roll Number:1
Subject-1 marks:60.0
Subject-2 marks:30.0
Subject-3 marks:45.0
Percentage: 45.00
Name :Ram
Roll Number:2
Subject-1 marks:60.0
Subject-2 marks:70.0
Subject-3 marks:75.0
Percentage: 68.33
The number of Students passed is 1
CO-PO Mapping
53
Data Structure Using JAVA Lab Manual School of CS&E, REVA University
Sl.N Programs
o POs PSOs
CO
54