DSA All Labs
DSA All Labs
LAB # 01
Class Activity:
Sample Program#1
import java.util.Scanner;
class ScannerTest{
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Sample Program#2
This program uses different string classes.
import java.io.*;
/** The Names class provides a single function, main, that will
* perform various manipulations of the name abc ijk xyz.
class Names {
/** Performs various string operations on the name ana kim xen.
firstInit = first.substring(0,1);
middleInit = middle.substring(0,1);
lastInit = last.substring(0,1); initials
= firstInit.concat(middleInit); initials
= initials.concat(lastInit);
System.out.println()
System.out.println(first + " " + middle + " " + last + " ");
System.out.println(initials);
System.out.println(last + ", " + first + " " + middle);
System.out.println(last + ", " + first + " " + middleInit +".");
System.out.println(first.toUpperCase() + " " + last.toUpperCase);
System.out.println(first + " equals ana is " + first.equals("ana"));
System.out.println(first + " equals ana (ignoring case) is " + first.equalsIgnoreCase("ana"));
System.out.println("The character at index 3 in " + middle + " is " +middle.substring(3,1));
System.out.println("The index of \"gerald\" within " + middle + " is " +
middle.indexOf("gerald"));
System.out.println("The index of \"gerald\" within " + last + " is " +last.indexOf("gerald"));
System.out.println();
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
Sample Program#3
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Sample Program#4
import java.io.*;
try{
byte bWrite [] = {65,66,67,68,69}; f =new
File("D:/filing/test.txt");
OutputStream os = new FileOutputStream(f);
for(int x=0; x < bWrite.length ; x++)
{ os.write( bWrite[x] ); // writes the bytes
} os.close();
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Lab Tasks
1. Write a program that takes your name, section and GPA as input and print it.
Code:
import java.util.Scanner; public class lab1{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
} Output:
2. Write a program that initialize five different strings and perform the following operations.
a. Concatenate all five stings
b. Convert first one string to uppercase
c. Convert fourth string to lowercase
d. Find the substring from the concatenated string from 8 to onward
e. Find the substring from the concatenated string from 2 to onward
Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
package lab;
public class lab1 {
public static void main(String[] args) {
String a = "Hello ", b = "To ", c = "A ", d = "Programming World", e = "!!";
}
Output:
3. Write a program that takes three numbers as input write it on a file and then read from the file
and print it.
Code:
package lab1;
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args){
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter Number1: ");
int no1 = input.nextInt();
System.out.print("Enter Number2: ");
int no2 = input.nextInt();
System.out.print("Enter Number3: ");
int no3 = input.nextInt();
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\myfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("Number1: "+no1+"\nNumber2: "+no2+"\nNumber3: "+no3);
bw.close();
SWE-203L: Data Structures and Algorithms SSUET/QR/114
}
}
}
Output:
Notepad:
4. Write a program that takes three numbers as input write it on a file and then read from the file,
convert them into character and print it
Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
package lab1;
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args){
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter no1: ");
int no1 = input.nextInt();
System.out.print("Enter no2: ");
int no2 = input.nextInt();
System.out.print("Enter no3: ");
int no3 = input.nextInt();
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\myfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(no1+"\n"+no2+"\n"+no3);
bw.close();
System.out.println("Reading from file:");
BufferedReader br = new BufferedReader(new FileReader(f));
String s;
while ((s = (br.readLine())) != null){
int i = Integer.parseInt(s);
System.out.println((char)i);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
Output:
Notepad:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Home Tasks
1. Write a program that take string as an input attempting to guess the secret word enters
letters one at a time. After each guess, the guess template is updated (if necessary) to
show which letters in the secret word match the letter guessed. This process continues
until the guess template matches the secret word choice of 7 wrong attempts. The
number of guesses is then output. For example:
LAB # 02
Array List and Vector in JAVA
Object
To implement Array List and Vector.
Lab Activity:
Sample Program#1
//displaying elements
System.out.println(alist);
//displaying elements
System.out.println(alist);
} }
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Sample Program#2
import java.util.ArrayList; public class
ArrayList<Integer>(); myNumbers.add(10);
myNumbers.add(15); myNumbers.add(20);
System.out.println(i);
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Sample Program#3
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new
Vector<String>(); //Adding elements using
add() method of List vec.add("Tiger");
vec.add("Lion"); vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of
Vector vec.addElement("Rat");
vec.addElement("Cat"); vec.addElement("Deer");
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Sample Program#4
import java.util.*;
public class VectorExample2 {
public static void main(String args[]) {
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);
//Display the vector elements
System.out.println("Values in vector: " +in);
//use remove() method to delete the first occurence of an element
System.out.println("Remove first occourence of element 200: "+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " +in);
//Remove the element at index 4
System.out.println("Remove element at index 4: " +in.remove(4));
System.out.println("New Value list in vector: " +in);
//Remove an element
in.removeElementAt(5);
//Checking vector and displays the element
System.out.println("Vector element after removal: " +in);
//Get the hashcode for this vector
System.out.println("Hash code of this vector = "+in.hashCode());
//Get the element at specified index
System.out.println("Element at index 1 is = "+in.get(1));
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
Lab Tasks
1. Write a program that initializes ArrayList which initializes 10 integers in it. Display all the
integers and sum of these integers.
Code:
package lab1;
import java.util.*;
public class lab1{
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
arr.add(6);
arr.add(7);
arr.add(8);
arr.add(9);
arr.add(10);
int count = 0;
for (int i:arr){
count += i;
}
System.out.println("Sum of Numbers: "+count);
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
2. Write a program that initialize Vector of String data type. Initialize 10 strings in it and perform
all the operations on it.
Code:
package lab1;
import java.util.*;
public class lab1{
public static void main(String[] args) {
Vector<String> x = new Vector<>();
x.add("Nabiha");
x.add("Hunaina");
x.add("Huzaifa");
x.add("Hanif");
x.add("Sobia");
x.add("Seemla");
x.add("Radeef");
x.add("Amna");
x.add("Bisma");
x.add("Aimen");
System.out.println("Elements are : "+x);
System.out.println("After removing a element :"+x.remove(3));
System.out.println("Element at index 1 is : "+x.get(1)); x.add("Hafsa");
System.out.println("After Adding Element : "+x);
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Home Tasks
1. Create a ArrayList storing string objects. Write a menu driven program which:
Code:
package lab1;
import java.util.*;
public class lab1 {
public static void main(String[] args)
{ ArrayList<String> menu = new ArrayList<>();
menu.add("Cold drink");
menu.add("Tikka");
menu.add("Biryani");
menu.add("Cheesy fries");
menu.add("wings");
System.out.println("\tMenu :");
for(String s:menu){ System.out.println("~"+s);
}
int biggest = 0,
index = 0;
for(int i = 0; i< menu.size(); i++){ String word =
menu.get(i);
if(word.length()>biggest){ biggest = word.length();
index = i;
}
}
System.out.println("Biggest String: "+menu.get(index));
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 03
Implementation of Recursive Procedure
Object
To implement
Recursive Procedures.
Sample Program #1
if (powerRaised != 0)
else
return 1;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
Lab Tasks
1. Write a program that implements factorial using recursive procedure.
Code:
package lab3;
public class lab3 {
public static void main(String[] args){
System.out.println("Factorial of 5: "+factorial(5));
}
public static int factorial(int n){
if(n==0)
return 1;
return n*factorial(n-1);
}
}
Output:
Code:
package Lab3;
public class Task2 {
public static void main(String[] args){
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.println("Fibonacci of 7: "+fibonacci(7));
}
Output:
Home Tasks
1. Write a program that implements Palindrome using recursive procedure.
Code:
package Lab3;
public class Task {
public static void main(String[] args) {
System.out.println("MOM is palindrome: "+palindrome("MOM"));
System.out.println("Moring is palindrome: "+palindrome("Bro"));
}
public static boolean palindrome(String s){
if(s.length()==0|| s.length()==1)
return true;
if(s.charAt(0)==s.charAt(s.length()-1)){
return palindrome(s.substring(1,s.length()-1));
}
return false;
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Code:
package Lab3;
import java.util.Scanner;
public class Task {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number to check sum: ");
int n = input.nextInt();
System.out.printf("Sum of %d numbers = %d\n",n,sum(n));
}
public static int sum(int n){
if (n==1)
return 1;
return n+sum(n-1);
}
}
Output:
Input: 50
Output: 2 digits
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Code:
package Lab3;
import java.util.Scanner;
public class Task{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Numbers to check digits: ");
int n = input.nextInt();
System.out.printf("%d has : %d digits\n",n,digitsChecker(n));
}
public static int digitsChecker(int n){
if (n==0)
return 0;
return 1+ digitsChecker(n/10);
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 04
Linear Array Implementation
Object
Implementing linear array and associated methods.
Task
1. Write a program to implement all basic operations in linear array (specified in linear array
class). Write a demo class to show the working of array.
Code:
package Lab4;
public class Task {
public static void main(String[] args) {
int[] arr = new int[5];
int length = arr.length;
for(int i=0; i<length; i++){
arr[i]= i+1;
}
// Traversing Array
for(int i=0; i<length; i++){
System.out.printf("arr[%d] = %d , ",i,arr[i]);
}
// Delting Elements
int k = 2;
for (int i=k; i<length-1; i++){
arr[i] = arr[i+1];
}
length -= 1;
System.out.println("\nArray after deleting Index 2: ");
for(int i=0; i<length; i++){
System.out.printf("arr[%d] = %d , ",i,arr[i]);
}
// Insertion
k = 2;
int j = length-1;
for (int i=j; i>k; i--){
SWE-203L: Data Structures and Algorithms SSUET/QR/114
arr[j] = arr[j-1];
}
arr[k] = 10;
length +=1;
System.out.println("\nArray after Inserting 10 at index 2");
for(int i=0; i<length; i++){
System.out.printf("arr[%d] = %d , ",i,arr[i]);
}
}
}
Output:
2. Add a method in the class that takes array and merge it with the existing one.
Code:
package Lab4;
import java.util.*;
public class Task {
public static void main(String[] args) {
int[] arr1 = {11,12,13,14,15};
int[] arr2 = {16,17,18,19};
System.out.println("Array 1: "+ Arrays.toString(arr1));
System.out.println("Array 2: "+ Arrays.toString(arr2));
int[] arr = merge(arr1,arr2);
System.out.println("Merged Array: " + Arrays.toString(arr));
}
public static int[] merge(int[] arr1, int[] arr2){
int length = arr1.length + arr2.length;
int[] arr = new int[length];
for(int i=0; i<length; i++){
if(i<arr1.length){
arr[i] = arr1[i];
SWE-203L: Data Structures and Algorithms SSUET/QR/114
}else{
arr[i] = arr2[i-arr2.length-1];
}
}
return arr;
}
}
Output:
3. Add a method in the same class that splits the existing array into two. The method should
search a key in array and if found splits the array from that index of the key
package Lab4;
import java.util.*;
public class Task {
public static void main(String[] args) {
int[] array = {11,12,13,14,15,16,17,18,19};
split(array, 3);
}
public static void split(int[] arr, int index){
int[] arr1 = new int[index+1];
int[] arr2 = new int[arr.length-index-1];
for (int i=0; i<arr.length; i++){
if(i<arr1.length){
arr1[i] = arr[i];
}else{
arr2[i-arr1.length] = arr[i];
}
}
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("After splitting at index: "+index);
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Home Task
1. Write a Java program to create all possible permutations of a given array of distinct
integers.
Example:
Input:
nums1 = {1, 2, 3, 4}
nums2 = {1, 2, 3}
Output:
Possible permutations
of the said array 1:
[1, 2, 3, 4]
[1, 2, 4, 3]
....
[4, 1, 3, 2]
[4, 1, 2, 3]
Possible permutations
of the said array 2:
[1, 2, 3]
[1, 3, 2]
...
[3, 2, 1]
[3, 1, 2]
Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
package Lab4;
import java.util.*;
public class Task {
public static void
main(String[] args)
{
Scanner input =
new
Scanner(System.in
);
int[] arr1 = new
int[3];
System.out.println
("\tArray 1:");
for (int i=0;
i<arr1.length; i++)
{
System.out.print("
Enter element "+
(i+1)+": ");
arr1[i] =
input.nextInt();
}
int[] arr2 = new
int[4];
System.out.println
("\n\tArray2");
for (int i=0;
i<arr2.length; i++)
{
System.out.print("
Enter element "+
(i+1)+": ");
arr2[i] =
input.nextInt();
}
System.out.println
("Permutations of
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Array 1:");
permute(arr1,0);
System.out.println
("\nPermutations
of Array 2:");
permute(arr2,0);
}
static void
permute(int[]
arr,int k){
for(int i = k; i <
arr.length; i++){
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
permute(arr, k+1);
temp = arr[k];
arr[k] = arr[i];
arr[i] = temp;
}
if (k == arr.length
-1){
System.out.println
(Arrays.toString(ar
r));
}
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 05
Sorting on Linear Array
Object
SWE-203L: Data Structures and Algorithms SSUET/QR/114
To sort a linear array using Selection Sort, Bubble Sort and Merge Sort.
Theory
Sorting is the process of arranging data into meaningful order so that you can analyze it more
effectively. For example, you might want to order sales data by calendar month so that you can
produce a graph of sales performance. You can use Discoverer to sort data as follows:
Algorithm for
Selection Sort
Algorithm for
Bubble Sort
MergeSort(arr, left,
right):
if left > right
return
mid = (left+right)/2
mergeSort(arr, left,
mid) mergeSort(arr,
mid+1, right)
merge(arr, left, mid,
right)
end
Lab Task
4. Write a program for Selection sort that sorts an array containing numbers, prints all the sort
values of array each followed by its location.
Code:
package Lab5;
import java.util.*;
5. Write a program that takes 10 numbers as input in an array. Sort the elements of array by
using Bubble sort. Print each iteration of the sorting process.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class Task{
public static void main(String[] args) {
int[] arr = new int[10];
Scanner sc = new Scanner(System.in);
for (int i = 0; i <arr.length; i++) {
System.out.print("Enter a number: ");
arr[i] = sc.nextInt();
}
bubbleSort(arr);
System.out.println("\nArray After Sort: "+Arrays.toString(arr));
SWE-203L: Data Structures and Algorithms SSUET/QR/114
}
public static void bubbleSort(int[] arr){
for(int i=arr.length-1; i>0; i--){
// ->>
for (int j=0; j<i; j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
System.out.println(Arrays.toString(arr));
}
}
}}}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
6. Write a program that takes 10 random numbers in an array. Sort the elements of array by
using Merge sort. Print each iteration of the sorting process.
Code:
package Task;
import java.util.*;
SWE-203L: Data Structures and Algorithms SSUET/QR/114
i++;
k++;
}
System.out.println("Given Array");
printArray(arr);
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.println("\nSorted array");
printArray(arr);
}
}
Output
Given Array
66 58 12 90 61 -17
Sorted Array
-17 12 58 61 66 90
Home Task
1. Declare an array of size n to store account balances. Initialize with values 0 to 1000000
and sort Account No’s according to highest balance values by using Quick sort, For e.g.:
Account No. 3547 Balance 28000
Account No. 1245 Balance 12000
Code:
package Task;
import java.util.*;
}
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
SWE-203L: Data Structures and Algorithms SSUET/QR/114
arr[j] = temp;
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 06
Searching in a Linear Array
Object
To find an element in linear array using Linear Search and Binary Search
Lab Task
7. Declare an array of size 10 to store account balances. Initialize with values 0 to 1000000.
Check all array if any value is less than 10000. Show message:
Account No .. Low Balance
Account No .. Low Balance
Code:
package Task;
import java.util.*;
int i;
for (i=0;i<arr.length;i++){
for (i=0;i<arr.length;i++){
if (arr[i]<10000){
System.out.println("Acount No "+(i+1)+" has low balance."+arr[i]);;
}
}
}
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Code:
import java.util.Scanner;
public class lab6dsa {
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.print("Search for :");
int k = input.nextInt();
int[] a1= {10,20,30,50,70,90};
int key = k;
System.out.println(key+" at index: "+linearSearch(a1, key));
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Home Task
1. Write a function called occurrences that, given an array of numbers A, prints all the
distinct values in A each followed by its number of occurrences. For example, if A = (28,
1, 0, 1, 0, 3, 4, 0, 0, 3), the function should output the following five lines (here separated
by a semicolon) “28 1; 1 2; 0 4; 3 2; 4 1”.
import java.util.HashSet;
import java.util.Scanner;
public class lab6dsa {
public static void main(String[] args){
int arri[] = {28,1,0,1,0,3,4,0,0,3};
HashSet<Integer> al = new HashSet<Integer>();
for(int i=0;i<arri.length;i++){
arri.add(arri[i]);
}
System.out.println("arr "+arri);
int[] arr = null;
for(int set : arr){
int count = 0;
for(int j=0;j<a.length;j++){
if(set==arri[j]){
count++;
}
}
System.out.println(set+" occurs "+count+" times");
}
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Code:
package lab1;
import java.util.Scanner; public class lab1{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Secret Word: ");
String word = input.nextLine().toLowerCase();
StringBuffer blank= new StringBuffer();
for(int i=0; i<word.length(); i++){
blank.append("_");
}
System.out.println(blank);
int wrongCount = 0, guessCount = 0;
do {
System.out.print("Guess a letter: ");
String letter = input.next();
int index = word.indexOf(letter);
if(index == -1) {
wrongCount++;
System.out.println(blank);
}
else{
blank.replace(index,index+1,letter);
if(word.indexOf(letter,index+1)!=-1){
int index2 = word.indexOf(letter, index+1);
blank.replace(index2,index2+1,letter);
}
System.out.println(blank);
guessCount++;
}
}
while(wrongCount<7 && word.equalsIgnoreCase(blank.toString())!=true);
if(word.equalsIgnoreCase(blank.toString())){
System.out.println("You Guessed the word in "+(guessCount)+" guesses");
}
else{
System.out.println("Game Over !");
}
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
2. Write a program that read a names from the given file ”Names” and searches for a
specific initial letter in the last name and write a new file “NewNames” with those
searched names.
Code:
package lab1;
import java.util.Scanner;
import java.io.*;
public class lab1 {
public static void main(String[] args) {
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter Initial to search name: ");
String x = input.next();
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
File f2 = new File("C:\\Users\\ivc13004adm\\OneDrive\\nextfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f2));
String s;
System.out.println("Searching for names with initial "+x+":");
while((s = br.readLine())!=null){
if(s.indexOf(x)==0){
System.out.println("-"+s);
}
}
br.close();
SWE-203L: Data Structures and Algorithms SSUET/QR/114
bw.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
Output:
Notepad:
Code:
package lab1;
import java.io.*;
public class lab1 {
public static void main(String[] args) {
try{
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\nextfile.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String s;
int count = 0;
while ((s = br.readLine())!=null){ String[] words = s.split(" ");
count = words.length;
}
br.close();
System.out.println("No of Words: "+count); }catch(Exception e){ e.printStackTrace();
}
}
}}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
Notepad:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Lab # 7
Object
Implementing singly linked list and associated operations.
Lab Tasks:
1. Write a program that can store 10 records of students in a link list manner and apply the
following operations on it.
a. View the list
b. Insert the elements in different locations of linked list and view it.
c. Search any element from the linked list
d. Delete record again view the list after deletion
Source Code:
package lab7;
public class LinkedList
{
Node head = null;
// static inner class
static class Node {
int data;
// connect each
node to next node
Node next;
public Node(int
data) {
this.data = data;
next = null;
}
}
public void
insertbegining(int data)
{
Node n = new
Node(data);
n.next= head;
head = n;
}
public void
insertAtPosition(Node
prev, int data){
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Node n = new
Node(data);
Node temp;
temp = prev.next;
prev.next = n;
n.next = temp;
}
public void
insertend(int data){
Node n = new
Node(data);
Node temp =
head;
Node prev = null;
while(temp!=null)
{
prev = temp;
temp =
temp.next;
}
prev.next = n;
n.next = null;
}
public void
delete(int data){
Node temp,
prev=null;
temp =head;
while(temp!=null
&& temp.data!=data){
prev = temp;
temp =
temp.next;
}
prev.next =
temp.next;
}
public void
searchNode(int data) {
Node current =
head;
int i = 1;
boolean flag =
false;
//Checks whether
list is empty
SWE-203L: Data Structures and Algorithms SSUET/QR/114
if(head == null) {
System.out.println("Lis
t is empty");
}
else {
while(current !=
null) {
//Compares
node to be found with
each node present in
the list
if(current.data == data)
{
flag = true;
break;
}
i++;
current =
current.next;
}
}
if(flag)
System.out.println("Ele
ment is present in the
list at the position : " +
i);
else
System.out.println("Ele
ment is not present in
the list");
}
public void
printList() {
Node temp =
head;
while(temp!=null)
{
System.out.println(tem
p.data);
temp =
temp.next;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
}
public static void
main(String[] args) {
// write your code here
System.out.println("Re
cord of Students are:
");
LinkedList ll =
new LinkedList();
Node first = new
Node(78);
ll.head = first;
Node second =
new Node(54);
first.next =
second;
Node third = new
Node(87);
second.next =
third;
Node fourth =
new Node(91);
third.next =
fourth;
Node fifth = new
Node(68);
fourth.next = fifth;
Node sixth = new
Node(75);
fifth.next = sixth;
Node seventh =
new Node(80);
sixth.next =
seventh;
Node eighth =
new Node(61);
seventh.next =
eighth;
Node ninth = new
Node(52);
eighth.next =
ninth;
Node tenth = new
Node(89);
ninth.next = tenth;
ll.printList();
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.println("\
nAfter Insertion");
ll.insertbegining(45);
ll.insertAtPosition(thir
d, 56);
ll.insertend(66);
ll.printList();
System.out.println("\
nSearching");
ll.searchNode(91);
System.out.println("\
nAfter Deletion");
ll.delete(52);
ll.printList();
}
}
Output:
Home Tasks:
1. Write a program
that reads the
name, age and
salary of 10 persons
and perform the
following operations
on it.
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Source Code:
import
lab7.LinkedList;
public class
Lab7_HTask1 {
Node head = null;
// static inner class
static class Node {
String data;
// connect each
node to next node
Node next;
public
Node(String data) {
this.data = data;
next = null;
}
}
public void
insertbegining(String
data){
Node n = new
Node(data);
n.next= head;
head = n;
}
public void
insertAtPosition(Node
prev, String data){
Node n = new
Node(data);
Node temp;
temp = prev.next;
prev.next = n;
n.next = temp;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
public void
insertend(String data){
Node n = new
Node(data);
Node temp =
head;
Node prev = null;
while(temp!=null)
{
prev = temp;
temp =
temp.next;
}
prev.next = n;
n.next = null;
}
public void
delete(String data){
Node temp,
prev=null;
temp =head;
while(temp!=null
&& temp.data!=data){
prev = temp;
temp =
temp.next;
}
prev.next =
temp.next;
}
public void
searchNode(String
data) {
Node current =
head;
int i = 1;
boolean flag =
false;
//Checks whether
list is empty
if(head == null) {
System.out.println("Lis
t is empty");
}
else {
SWE-203L: Data Structures and Algorithms SSUET/QR/114
while(current !=
null) {
//Compares
node to be found with
each node present in
the list
if(current.data == data)
{
flag = true;
break;
}
i++;
current =
current.next;
}
}
if(flag)
System.out.println("Ele
ment is present in the
list at the position : " +
i);
else
System.out.println("Ele
ment is not present in
the list");
}
public void
printList() {
Node temp =
head;
while(temp!=null)
{
System.out.println(tem
p.data);
temp =
temp.next;
}
}
public static void
main(String[] args) {
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.println("Na
mes of 10 person: ");
Lab7_HTask1 ll =
new Lab7_HTask1();
Node first = new
Node("Hassan");
ll.head = first;
Node second =
new Node("Omer");
first.next =
second;
Node third = new
Node("Usama");
second.next =
third;
Node fourth =
new Node("Hasnain");
third.next =
fourth;
Node fifth = new
Node("Hannan");
fourth.next = fifth;
Node sixth = new
Node("Zohaib");
fifth.next = sixth;
Node seventh =
new Node("Khubaib");
sixth.next =
seventh;
Node eighth =
new Node("Ammar");
seventh.next =
eighth;
Node ninth = new
Node("Usman");
eighth.next =
ninth;
Node tenth = new
Node("Furqan");
ninth.next = tenth;
ll.printList();
System.out.println("\
nAfter Insertion");
SWE-203L: Data Structures and Algorithms SSUET/QR/114
ll.insertbegining("Muz
ammil");
ll.insertAtPosition(four
th, "Asad");
ll.insertend("Ali");
ll.printList();
System.out.println("\
nSearching");
ll.searchNode("Omer")
;
System.out.println("\
nAfter Deletion");
ll.delete("Asad");
ll.printList();
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 08
Doubly Linked List implementation of the list ADT
Object
Implementing doubly linked list and associated operations.
Lab Task
1. Write a program that can insert the records of employees in a link list. The record includes
employees’ name, designation, department and company name.
a. The program should be able to insert the record as first, last and as middle node
in the list.
b. The program should be able to search any record.
Code:
package Lab8;
import
Lab7.LinkedList
;
class
DoublyLinkedLis
t {
class Link
{
String
name,
designation,
department,
company;
Link
previous;
Link
next;
public
Link(String n,
String des,
String dep,
String com ){
this.name = n;
this.designatio
n = des;
SWE-203L: Data Structures and Algorithms SSUET/QR/114
this.department
= dep;
this.company =
com;
}
}
//Initially,
heade and tail
is set to null
Link head,
tail = null;
//add a
node to the
list
public void
addNode(String
n, String des,
String dep,
String com ) {
Link
newLink = new
Link(n, des,
dep, com);
//if
list is empty,
head and tail
points to
newNode
if(head
== null) {
head = tail =
newLink;
//head's
previous will
be null
head.previous =
null;
//tail's next
will be null
tail.next =
SWE-203L: Data Structures and Algorithms SSUET/QR/114
null;
}
else {
//add newNode
to the end of
list. tail-
>next set to
newNode
tail.next =
newLink;
//newNode-
>previous set
to tail
newLink.previou
s = tail;
//newNode
becomes new
tail
tail = newLink;
//tail's next
point to null
tail.next =
null;
}
}
public void
insertAt(int
index, String
n, String des,
String dep,
String com) {
int
counter = 0;
Link
newLink = new
Link(n, des,
dep, com);
Link
link = head;
if(head
== null){
SWE-203L: Data Structures and Algorithms SSUET/QR/114
head = newLink;
tail = newLink;
return;
}
while(counter<i
ndex-1){
link =
link.next;
counter++;
}
Link
temp =
link.next;
link.next =
newLink;
link.next.next
= temp;
}
public void
print() {
Link
current = head;
if(head
== null) {
System.out.prin
tln("Doubly
linked list is
empty");
return;
}
int i =
1;
while(current !
= null) {
//Print each
node and then
go to next.
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.prin
tln("\nEmployee
"+i+":");
System.out.prin
tln("Name:
"+current.name)
;
System.out.prin
tln("Designatio
n:
"+current.desig
nation);
System.out.prin
tln("Department
:
"+current.depar
tment);
System.out.prin
tln("Company:
"+current.compa
ny);
current =
current.next;
i+
+;
}
}
public void
search(String
name){
if(head
== null){
System.out.prin
tln("List is
empty.");
return;
}
int
counter = 0;
Link
link = head;
int pos
= -1;
SWE-203L: Data Structures and Algorithms SSUET/QR/114
while(link !=
null && pos ==
-1){
if(name.equalsI
gnoreCase(link.
name)){
pos =
counter+1;
break;
}
link =
link.next;
counter++;
}
if(pos != -1){
System.out.prin
tln(name+"
Found at
position:
"+pos);
}else{
System.out.prin
tln("Item not
Found!");
}
public
static void
main(String[]
args){
DoublyLinkedLis
t dll = new
DoublyLinkedLis
t();
dll.addNode("Mo
hsin Khan
Lodhi", "Senior
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Developer","IT"
,"Oracle");
dll.addNode("Sa
lman Junaid",
"Web
Developer",
"Web
Designing",
"Facebook");
dll.addNode("Mu
hammad
Hammad","Admini
strator",
"Administration
", "Google");
dll.insertAt(1,
"Abrar Ali",
"Assurance
Testing","Testi
ng","Microsoft"
);
dll.print();
System.out.prin
tln("\
nSearching:");
dll.search("Moh
sin Khan
Lodhi");
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Home Task
1. Write a program which includes these 3 classes
break;
}
link = link.next;
counter++;
}
if (pos != -1) {
System.out.println(data + " Found at position: " +
pos);
} else {
System.out.println("Item not Found!");
}
}
}
DoublyLL Class
Code:
package Lab8.HomeTask;
Output ( DoublyLL
Class):
Output ( Demo
Class):
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 09
Stack Implementation
Object
To implement Stack as Arrays and linked list.
Sample Program
#1
public class
StackAsLinkedLi
st {
StackNode
root;
static
class StackNode
{
int
data;
StackNode next;
StackNode(int
data) {
this.data =
data; }
}
public
boolean
isEmpty()
{
if
(root == null)
{
return true;
}
else
return false;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
public void
push(int data)
{
StackNode
newNode = new
StackNode(data)
;
if
(root == null)
{
root = newNode;
}
else {
StackNode temp
= root;
root = newNode;
newNode.next =
temp;
}
System.out.prin
tln(data + "
pushed to
stack");
}
public int
pop()
{
int
popped =
Integer.MIN_VAL
UE;
if
(root == null)
{
System.out.prin
tln("Stack is
Empty");
}
else {
popped =
SWE-203L: Data Structures and Algorithms SSUET/QR/114
root.data;
root =
root.next;
}
return
popped;
}
public int
peek()
{
if
(root == null)
{
System.out.prin
tln("Stack is
empty");
return
Integer.MIN_VAL
UE;
}
else {
return
root.data;
}
}
// Driver
code
public
static void
main(String[]
args)
{
StackAsLinkedLi
st sll = new
StackAsLinkedLi
st();
sll.push(10);
sll.push(20);
SWE-203L: Data Structures and Algorithms SSUET/QR/114
sll.push(30);
System.out.prin
tln(sll.pop()
System.out.prin
tln("Top
element is " +
sll.peek());
}
Output:
LAB TASK
1. Write a program
to create Stack
that can take
input random
candies color (i.e.
yellow, green,
orange, red etc)
and stored in
order. The user
likes any one of
the colored candy
to eat so he takes
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Original
stack: Yellow-
>green->orange-
>yellow->red
Updated
stack: Green-
>orange->red i.e.
yellow is removed
Code:
package Lab9;
import java.util.Scanner;
public class CandiesStack {
StackNode root;
class StackNode{
String data;
StackNode next;
StackNode(String data){
this.data = data;
}
}
boolean isEmpty(){
if(root == null)
return true;
else
SWE-203L: Data Structures and Algorithms SSUET/QR/114
return false;
}
void push(String data){
StackNode newNode = new StackNode(data);
if (root == null){
root = newNode;
}else{
StackNode temp = root;
root = newNode;
root. next = temp;
}
}
String pop(){
if(root == null){
System.out.println("Stack Underflow !");
return "";
}else{
StackNode popped = root;
root = root.next;
return popped.data;
}
}
if(candy.equalsIgnoreCase(root.data)){
System.out.println("Here's your "+candy+" candy");
root = root.next;
return candy;
void display(){
if(root ==null){
System.out.println("The stack is empty!");
}else{
System.out.println("Stack contains: ");
StackNode counter = root;
while(counter != null){
System.out.println("-"+counter.data);
counter = counter.next;
}
System.out.println();
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
HOME TASK
1. Write a program to convert Infix expression into postfix expression by stack using linked list.
A + ( B * C - ( D / E | F ) * G ) * H
Code:
package Lab9;
import
java.util.Stack
;
public class
HomeTask {
public
static void
main(String[]
args){
String
exp = "A+(B*C-
(D/E+F)*G)*H";
System.out.prin
SWE-203L: Data Structures and Algorithms SSUET/QR/114
tln("Infix
notation:
"+exp);
System.out.prin
tln(infixToPost
fix(exp));
}
static int
Prec(char ch){
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static
String
infixToPostfix(
String exp)
{
String result =
new String("");
Stack<Character
> stack = new
Stack<>();
SWE-203L: Data Structures and Algorithms SSUET/QR/114
for
(int i = 0;
i<exp.length();
++i)
{
char c =
exp.charAt(i);
if
(Character.isLe
tterOrDigit(c))
result += c;
else if (c ==
'(')
stack.push(c);
else if (c ==
')')
while (!
stack.isEmpty()
&&
stack.peek() !=
'(')
result +=
stack.pop();
stack.pop();
else // an
operator is
encountered
while (!
SWE-203L: Data Structures and Algorithms SSUET/QR/114
stack.isEmpty()
&& Prec(c)
<=
Prec(stack.peek
())){
result +=
stack.pop();
stack.push(c);
//
pop all the
operators from
the stack
while (!
stack.isEmpty()
){
if(stack.peek()
== '(')
return "Invalid
Expression";
result +=
stack.pop();
}
return result;
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 10
Stack ADT Implementation
Object
Sample Program#1
Code:
package Lab10;
import
java.util.*;
public class
StackDemo {
static void
showpush(Stack
st, int a) {
st.push(new
Integer(a));
System.out.prin
tln("push(" + a
+ ")");
System.out.prin
SWE-203L: Data Structures and Algorithms SSUET/QR/114
tln("stack: " +
st);
}
static void
showpop(Stack
st) {
System.out.prin
t("pop -> ");
Integer
a = (Integer)
st.pop();
System.out.prin
tln(a);
System.out.prin
tln("stack: " +
st);
}
public
static void
main(String
args[]) {
Stack
st = new
Stack();
System.out.prin
tln("stack: " +
st);
showpush(st,
42);
showpush(st,
66);
showpush(st,
99);
showpop(st);
showpop(st);
showpop(st);
try {
SWE-203L: Data Structures and Algorithms SSUET/QR/114
showpop(st);
} catch
(EmptyStackExce
ption e) {
System.out.prin
tln("empty
stack");
}
}
}
Output:
Lab Task
1. Convert and evaluate the expression from infix to postfix using Stack ADT class.
(A+B) * (C-D)
Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
package Lab10;
import java.util.Stack;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.isEmpty() &&
stack.peek() != '(')
result += stack.pop();
stack.pop();
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
result += stack.pop();
}
stack.push(c);
}
Output:
Home Task
1. Convert and evaluate the expression from infix to postfix using Stack ADT class.
A + ( B * C - ( D / E | F ) * G ) * H
Code:
package Lab10;
import java.util.*;
if(Character.isDigit(c))
stack.push(c - '0');
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 '*':
SWE-203L: Data Structures and Algorithms SSUET/QR/114
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
static int Prec(char ch){
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.isEmpty() &&
stack.peek() != '(')
result += stack.pop();
stack.pop();
}
else // an operator is encountered
{
SWE-203L: Data Structures and Algorithms SSUET/QR/114
result += stack.pop();
}
stack.push(c);
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 11 Queues
Implementation
Object:
FIFO queue implementation using double end. Sample
Program 1:
Code:
package Lab11;
public class
QueueLinkedList {
class Node{ int data; Node next;
Node(int key){ this.data = key;
this.next=null;
}
}
Node front, rear; public QueueLinkedList() {
this.front = null; this.rear = null;
}
void enqueue(int key) { Node temp = new Node(key); if
(this.rear == null) { this.front = this.rear = temp; return;
}
this.rear.next = temp; this.rear = temp;
}
Node dequeue() { if (this.front == null) return
null; Node temp = this.front; this.front =
this.front.next; if (this.front == null) this.rear = null;
return temp;
}
public static void printList(QueueLinkedList list) { Node currentNode = list.front;
System.out.print("Linked List Elements: "); while (currentNode != null)
{System.out.print(currentNode.data + " "); currentNode = currentNode.next;
}
System.out.println();
}
public static void main(String[] args) { QueueLinkedList q = new QueueLinkedList();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3); printList(q);
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.println("D
equeued item is " +
q.dequeue().data); printList(q);
}}
Output:
Lab Tasks:
1. Write a program
to implement queue
using double end.
Code:
package Lab11;
public class QueueArray { private static int front, rear, capacity; private
static int queue[];
QueueArray(int c)
{
front = rear = 0; capacity = c;
queue = new int[capacity];
}
}
}
// traverse front to rear and print elements for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
}
}
QueueArray.queueDequeue(); QueueArray.queueDequeue();
System.out.printf("\n\
nafter two node
deletion\n\n");
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Home Tasks:
1. Write a program that processes a group of input lines. Each input line contains an 'A' for
arrival or a 'D' for departure, and a license plate number. Cars are assumed to arrive and
depart in the order specified by the input. The program should: a) Print a message whenever
a car arrives or departs
b) When a car arrives, the message should specify whether or not there is a room
for the car in the garage. If there is no room, the car leaves without entering the garage.
c) When a car departs, the message should include the number of times that the
car was moved out of the garage to allow other cars to depart.
Code:
package Lab11;
public class lab11 { static class QueueArray { private static int front, rear,
capacity; private static int queue[];
QueueArray(int c)
{ front = rear = 0; capacity = c;
queue = new int[capacity];
}
System.out.printf("\
nThere are no cars.
Empty Queue\n");
return;
SWE-203L: Data Structures and Algorithms SSUET/QR/114
// decrement rear
rear--;
}
}
// traverse front to rear and print elements for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
}
System.out.println();
}
QueueArray.queueDequeue();
QueueArray.queueDisplay();
QueueArray.queueDequeue();
QueueArray.queueDisplay();
QueueArray.queueDequeue(); QueueArray.queueDisplay();
QueueArray.queueDequeue();
QueueArray.queueDisplay();
QueueArray.queueDequeue();
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LAB # 12
Implementation of Binary Search Tree
OBJECT:
Algorithm to implement binary search tree.
Sample Program:
Code:
package Lab12;
public class BinarySearchTree {
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
//Assign data to the new node, set left and right children to null
this.data = data;
this.left = null;
this.right = null; } }
//Represent the root of binary tree
public Node root;
public BinarySearchTree(){
root = null; }
void insert(int key) {
root = insert_Recursive(root, key);
} //insert() will add new node to the binary search tree
Node insert_Recursive(Node root, int key) {
//tree is empty
if (root == null) {
root = new Node(key);
return root; }
//traverse the tree
if (key < root.data) //insert in the left subtree
root.left = insert_Recursive(root.left, key);
else if (key > root.data) //insert in the right subtree
root.right = insert_Recursive(root.right, key);
// return pointer
SWE-203L: Data Structures and Algorithms SSUET/QR/114
return root; }
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Lab # 13
Graph And Graph Traversal Objects Objective:
Implementing graph using BFS and DFS Sample
Program:
Code:
package Lab13;
// set as
false)
boolean visited[] = new boolean[V];
// Create a
queue for BFS
LinkedList<Inte
ger> queue =
new
LinkedList<Inte
ger>();
// Mark the current node as visited and enqueue
it visited[s]=true; queue.add(s);
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s+" ");
// Get all
adjacent
vertices of the
dequeued vertex
s
// If a
adjacent has
not been
visited, then
mark it
// visited and
enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver
method to
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.prin
tln(" Breadth
First Traversal
" +
"(starting from
vertex 2)");
g.BFS(2);
} }
Output:
Lab Task:
1. Implement
BFS and DFS on
the given graph.
SWE-203L: Data Structures and Algorithms SSUET/QR/114
Code:
package Lab13;
import
java.util.*;
//
Constructor
@SuppressWarnin
gs("unchecked")
DepthGraph(int
v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// A
function used
by DFS
void DFSUtil(int v, boolean visited[])
{
//
Mark the
SWE-203L: Data Structures and Algorithms SSUET/QR/114
current node
as visited and
print it
visited[v] =
true;
System.out.prin
t(v + " ");
//
Recur for all
the vertices
adjacent to
this
//
vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) { int n = i.next();
if (!visited[n]) DFSUtil(n,
visited);
}
}
// The
function to do
DFS traversal.
It uses
recursive
// DFSUtil()
void DFS()
{
//
Mark all the
vertices as not
visited(set as
// false by default in java)
boolean visited[] = new boolean[V];
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
//
Constructor
BreadthGraph(in
t v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
//
Create a queue
for BFS
LinkedList<Inte
ger> queue =
new
SWE-203L: Data Structures and Algorithms SSUET/QR/114
LinkedList<Inte
ger>();
// Mark the current node as visited and enqueue
it visited[s]=true; queue.add(s);
while (queue.size() != 0)
{
// Dequeue a
vertex from
queue and print
it
s = queue.poll();
System.out.print(s+" ");
// Get all
adjacent
vertices of the
dequeued vertex
s
// If a
adjacent has
not been
visited, then
mark it
// visited and
enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114
// Driver
method to
public static void main(String args[])
{
// For
BFS
BreadthGraph g
= new
BreadthGraph(5)
;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 0);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 1);
g.addEdge(2, 4);
g.addEdge(3, 0);
g.addEdge(4, 2);
System.out.prin
tln("Following
is Breadth
First Traversal
");
g.BFS(2);
// For
DFS
DepthGraph g2 =
new
DepthGraph(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2); g2.addEdge(0,
3); g2.addEdge(1, 0);
g2.addEdge(1, 2); g2.addEdge(2,
0); g2.addEdge(2, 1);
g2.addEdge(2, 4); g2.addEdge(3,
0); g2.addEdge(4, 2);
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.prin
tln("\
nFollowing is
Depth First
Traversal");
g2.DFS();
} }
Output:
Home Task:
1. Implement
BFS and DFS on
the below given
graph.
Code:
package Lab13; import
java.util.*; import
java.io.*;
private
int V; // No.
of vertices
//
Constructor
@SuppressWarnin
gs("unchecked")
DepthGraph(int
v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// A
function used
by DFS
void DFSUtil(int v, boolean visited[])
{
//
Mark the
current node as
visited and
print it
visited[v] = true;
System.out.print(v + " "); // Recur
for all the vertices adjacent to this
//
vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) { int n = i.next();
SWE-203L: Data Structures and Algorithms SSUET/QR/114
if (!visited[n]) DFSUtil(n,
visited);
}
}
// The
function to do
DFS traversal.
It uses
recursive
// DFSUtil()
void DFS()
{
//
Mark all the
vertices as not
visited(set as
// false by default in java)
boolean visited[] = new boolean[V];
//
Constructor
BreadthGraph(in
t v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
SWE-203L: Data Structures and Algorithms SSUET/QR/114
//
Create a queue
for BFS
LinkedList<Inte
ger> queue =
new
LinkedList<Inte
ger>();
// Mark the current node as visited and enqueue
it visited[s]=true; queue.add(s);
while (queue.size() != 0)
{
// Dequeue a
vertex from
queue and print
it
s = queue.poll();
System.out.print(s+" ");
// Get all
adjacent
vertices of the
SWE-203L: Data Structures and Algorithms SSUET/QR/114
dequeued vertex
s
// If a
adjacent has
not been
visited, then
mark it
// visited and
enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
}
public static void main(String[] args) {
System.out.prin
tln("Breadth
First Traversal
:");
BreadthGraph g
= new
BreadthGraph(80
);
g.addEdge(40,20);
g.addEdge(40,10);
g.addEdge(20,10);
g.addEdge(20,30);
g.addEdge(10,30);
g.addEdge(30,60);
g.addEdge(50,70);
g.addEdge(60,70);
g.BFS(40);
SWE-203L: Data Structures and Algorithms SSUET/QR/114
System.out.prin
tln("\nDepth
First Traversal
:");
SWE-203L: Data Structures and Algorithms SSUET/QR/114
g2.DFS();
} }
Output:
LAB # 14
Implementing Hashing techniques and using HashTable ADT and
Collision Resolution Techniques
Object
Implementing Hashing techniques with collision resolution
Sample Program:
Code:
package Lab14;
import java.util.*;
public class HT {
public static void main(String[] args) {
Hashtable<String, Integer> ht = new Hashtable<>();
ht.put("arif", 10);
ht.put("saleem", 30);
ht.put("wasif", 20);
System.out.println("Size of map is:- " + ht.size());
System.out.println(ht);
if (ht.containsKey("arif")) { Integer a = ht.get("arif");
System.out.println("value for key" + " \"arif\" is:- " +
a); } } }
Output:
Lab Task:
1. Write a class to maintain a hash function to implement a digit-folding approach in the hash
function. Your program should work for any array size and any key length. Use linear probing.
Code:
package Lab14;
import java.util.Scanner;
n /= 10;
numDigits++;
}
return numDigits; } }
Output:
Home Task:
1. Enter data of a cricket team 11 players which is supposed to be a hash table value and insert runs
of each player as a data, find out key treat’s Rank# of a player.
For example: Runs are 30 mod by 11 which is index no 8; rank#8 is a rank of a team member. (Use
HashTable ADT class)
Code:
package Lab14;
import java.util.*;
rankFinder(team); }
public static void rankFinder(Hashtable table) {
int counter = 0;
ArrayList<Integer> ranks = new ArrayList<>();
ArrayList<String> members = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
Set<String> keys = table.keySet();
for (String key : keys) {
int rank = (int) table.get(key) % 11;
if (rank==0){
rank++; }
while (ranks.contains(rank)) {
rank++;
}
ranks.add(rank);
members.add(key);
scores.add((int)table.get(key));
counter++; }
Sort(ranks, members,scores);
for (int i=0; i<11; i++){
System.out.printf("%s - scores: %d - rank: %d\
n",members.get(i),scores.get(i),ranks.get(i)); } }
static void Sort(ArrayList<Integer> ranks, ArrayList<String>
members, ArrayList<Integer> scores) {
int n = ranks.size();
int n2 = n;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (ranks.get(j - 1) > ranks.get(j)) {
//swap rank
temp = ranks.get(j - 1);
ranks.set(j-1,ranks.get(j));
ranks.set(j, temp);
//swap members
String temp2 = members.get(j - 1);
members.set(j - 1, members.get(j));
members.set(j, temp2);
//swap scores
int temp3 = scores.get(j-1);
Output: