Search

Java - Data Structures - non linear - Binary Tree from the scratch

 

package datastructures.linear;

public class TreeFromTheScratch {
public static void main(String[] args) {
TreeImpl tree = new TreeImpl();
tree.insert(10);
tree.insert(5);
tree.insert(15);
tree.insert(6);
tree.insert(1);
tree.insert(8);
tree.insert(12);

System.out.println(("6 "+(tree.find(6)?"Found":"Not Found")));
System.out.println(("7 "+(tree.find(7)?"Found":"Not Found")));
}
}

class TreeImpl{
private Node root;

public void insert(int value){
var newNode = new Node(value);
if(null==root){
root = newNode;
return;
}
var current= root;
while(true){
if(current.value>value){
if(current.leftChild==null){
current.leftChild = newNode;
break;
}
current = current.leftChild;
} else {
if(current.rightChild==null){
current.rightChild = newNode;
break;
}
current = current.rightChild;
}
}
}

public boolean find(int value){
var current = root;
while (current!=null){
if(current.value==value){
return true;
} else if(current.value>value){
current = current.leftChild;
} else {
current = current.rightChild;
}
}
return false;
}

private class Node{
private int value;
private Node leftChild;
private Node rightChild;

public Node(int value) {
this.value = value;
}

@Override
public String toString() {
return "Node{" +
"value=" + value +
", leftChild=" + ((null!=leftChild)?leftChild.value:"null") +
", rightChild=" + ((null!=rightChild)?rightChild.value:"null") +
'}';
}
}
}

 

Java - Data Structures - Creating HashMap using array and LinkedLists

Collision Resolved by Using Changing Technique

 

package datastructures.linear;

import java.util.LinkedList;

public class HashMapFromArray {
public static void main(String[] args) {
HashMapArray obj = new HashMapArray();

obj.put(0, "Data 1");
obj.put(3,"Data 3");
obj.put(13,"Data 13");
obj.put(23,"Data 23");
obj.put(43,"Data 43");
obj.put(2352,"Data 2352");
obj.put(972,"Data 972");

obj.get(0);
obj.get(3);
obj.get(13);
obj.remove(3);
obj.get(3);
obj.get(13);
obj.get(2352);

//obj.display();
}
}

class HashMapArray {
private LinkedList<Entry>[] hashmap = new LinkedList[10];

public void put(int key, String value) {
var newKey = getHash(key);

//If there are no data in the index,initiate new list
if (null == hashmap[newKey])
hashmap[newKey] = new LinkedList<Entry>();

//If the Item already existing in the list,replace the value
for (var entry: hashmap[newKey])
if(entry.key==key){
entry.value = value;
return;
}

//If item not in the array,add value as a new item
hashmap[newKey].addLast(new Entry(key, value));
}

public void get(int key) {
var newKey = getHash(key);
var currentData = hashmap[newKey];
boolean flag = false;
if (null == currentData)
throw new IllegalArgumentException();
else
for (var dataObj : currentData)
if(dataObj.key==key) {
System.out.println(dataObj.value);
flag = true;
break;
}
System.err.println((!flag)?key+" - Not Fond":"");
}

public void remove(int key){
var newKey = getHash(key);
var currentData = hashmap[newKey];
boolean flag = false;
if (null == currentData)
throw new IllegalArgumentException();
else
for (var dataObj : currentData)
if(dataObj.key==key) {
currentData.remove(dataObj);
System.out.println("Done");
flag = true;
break;
}
System.err.println((!flag)?"Error":"");
}

private int getHash(int key) {
return (key >= hashmap.length) ? key % hashmap.length : key;
}

public void display() {
System.out.println(hashmap);
}

private class Entry {
private int key;
private String value;

Entry(int key, String value) {
this.key = key;
this.value = value;
}
}
}

 GitHub Url

Java - Data Structures - LinkedList Example

package datastructures.linear;

import java.util.*;
import java.util.stream.Collectors;

public class LinkListExample {
public static void main(String[] arg){
LinkedList<Integer> ll = new LinkedList<Integer>();

for (int i=0;i<10;i++)
//Adding data
ll.add((int) Math.round(Math.random()*100));

System.out.println("Initial LinkedList " + ll);

ll.set(1, 55);
System.out.println("Updated LinkedList " + ll);

ll.add(1, 66);
System.out.println("Updated LinkedList " + ll);

ll.addFirst(11);
ll.addLast(99);
System.out.println("After Adding the first and Last Element" + ll);

ll.remove(3);
System.out.println("After the Index Removal " + ll);

ll.remove("99");
System.out.println("After the Object Removal " + ll);

//Removing first and last element from the array
ll.removeFirst();
ll.removeLast();
System.out.println("After Adding the first and Last Element" + ll);

//Searching Item in the Array
System.out.println(((ll.contains(45))?"45 found":"45 not found"));

//Iterate linklist
//using for loop
for (int j=0;j<ll.size();j++)
System.out.print(ll.get(j)+",");
System.out.println();
//Using Iterator
Iterator it = ll.iterator();
while (it.hasNext())
System.out.print(it.next()+",");
}
}

Java - Logics - Palindrome word Checker

package logics.words;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.stream.Collectors;

public class PalindromeWordsChecker {
public static void main(String[] arg){
Scanner scanner = new Scanner(System.in);
boolean flag = true;
ArrayList<Character> wordCheck;
int count;
String scan = "";
do {
System.out.println();
System.out.print("Enter Word : ");
try {
scan = scanner.nextLine().toLowerCase();
} catch (Exception e){
scan = null;
System.err.println("Error in read Line :"+e.getMessage());
}
if(scan.isEmpty()||scan.length()<2||scan.isBlank()) continue;
flag = true;
wordCheck = new ArrayList<>(
scan.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList()));
count = wordCheck.size()-1;
for (int i = 0;i<wordCheck.size()/2;i++){
if(wordCheck.get(i) !=wordCheck.get(count)){
flag = false;
break;
}
count--;
}
if(flag){
System.out.println(scan+" is palindrome word");
} else {
System.err.println(scan+" is NOT palindrome word");
}
} while(!scanner.equals("q"));
}
}

GitHub Link


Java - Data Structures - Queue Example

 Elements are processed in the First In First Out (FIFO) manner

Those Queues that are present in the util package are known as Unbounded Queues.

Those Queues that are present in the util. concurrent packages are known as bounded Queues.

Since Queue is an interface, It requires a concrete class for the declaration.

The most common classes are the LinkedList, PriorityQueue, ArrayBlockingQueue, and ArrayDeque




Methods of Java Queue Interface

Method

Description

boolean add(object)

It is used to insert the specified element into this queue and return true upon success.

boolean offer(object)

It is used to insert the specified element into this queue.

Object remove()

It is used to retrieve and removes the head of this queue.

Object poll()

It is used to retrieve and remove the head of this queue or returns null if this queue is empty.

Object element()

It is used to retrieve but does not remove, the head of this queue.

Object peek()

It is used to retrieve, but does not remove, the head of this queue, or returns null if it is empty.



Code Example
package datastructures.linear;

import java.util.*;

public class QueueExample {

public static void main(String[] arg){

/*
Since Queue is an interface, It requires a concrete class for the declaration.
The most common classes are the LinkedList and PriorityQueue and ArrayDeque
Methods of Java Queue Interface

* boolean add(object)
- It is used to insert the specified element into this queue and return true upon success.
* boolean offer(object)
- It is used to insert the specified element into this queue.
* Object remove()
- It is used to retrieves and removes the head of this queue.
* Object poll()
- It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.
* Object element()
- It is used to retrieves, but does not remove, the head of this queue.
* Object peek()
- It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
*/

//Queue implementation Using One Dimensional Array
OneDimensionalArrayAsAQueue qu1 = new OneDimensionalArrayAsAQueue(5);
qu1.runQueue();

QueueExampleRun pq = new QueueExampleRun(new PriorityQueue<>());
pq.runQueue();
QueueExampleRun ad = new QueueExampleRun(new ArrayDeque<>());
ad.runQueue();
QueueExampleRun ll = new QueueExampleRun(new LinkedList<>());
ll.runQueue();
}
}

class QueueExampleRun extends CommonMethods{

QueueExampleRun(Queue<Integer> queue) {
super(queue);
}

public void runQueue(){
addData();
displayData();
Scanner scanner = new Scanner(System.in);
int val = 0;
do {
System.out.println();
System.out.print("Enter Value : ");
val = scanner.nextInt();
addSingleItemToQueue(val);
displayData();
} while (val!=99);

int exit = 1;
do {
exit = scanner.nextInt();
removeItemFromQueue();
// displayData();
} while(exit!=0);
}
}

class OneDimensionalArrayAsAQueue{
int startPointer,endPointer;
int queueSize;
static int[] q1;

OneDimensionalArrayAsAQueue(){
startPointer = 0;
endPointer = 0;
queueSize = 5;
}

OneDimensionalArrayAsAQueue(int size){
queueSize = size;
q1 = new int[queueSize];
}

void runQueue(){
for (int i=0;i<5;i++)
enQueue((int) Math.round(Math.random()*100));
display();
deQueue();
display();
deQueue();
display();
deQueue();
display();
deQueue();
display();
deQueue();
display();
deQueue();
}

/*
Used for insert Data
Logic - if it isn't full ( array size = endPointer ),
insert data to the array and increase pointer by 1
*/
void enQueue(int value){
if(queueSize==endPointer){
System.out.println("Queue is full");
} else {
q1[startPointer] = value;
startPointer++;
}
}

/*
Used for remove Item from the Queue
Since Queue are FIFO( First In First Out ), Removing should start from the begging of the array
All other items should shifted to 1 position up
*/
void deQueue(){
if(startPointer==0){
System.out.println("Queue is empty");
} else {
for (int i=0;i<startPointer-1;i++)
q1[i] = q1[i+1];
startPointer--;
}
}

void display(){
if(startPointer==0){
System.out.println("Queue is empty");
} else {
System.out.println();
for (int i=0;i<startPointer;i++) {
System.out.println(q1[i]);
}
}
}
}

abstract class CommonMethods{
Queue<Integer> queue;

CommonMethods(Queue<Integer> queue){
this.queue = queue;
}

public void addData(){
//Adding Data to Queue
for (int i=0;i<5;i++)
queue.add(((int) Math.round(Math.random()*100)));
}

public void removeItemFromQueue(){
System.out.println("Removing Item using remove = "+queue.remove());

System.out.println("Removing Item using poll = "+queue.poll());
}

public void viewTopItemInQueue(){
System.out.println("View top item using element = "+queue.element());

System.out.println("View top item using peek = "+queue.peek());
}

public void addSingleItemToQueue(int value){
//Add Item to Queue
if(queue.add(value)) System.out.println("Added Item to Queue using Add method "); else System.out.println("Error in Adding Data to Queue");

//Add data using offer method
if(queue.offer(value)) System.out.println("Added Item to Queue using offer method"); else System.out.println("Error in Adding Data to Queue");
}

public void displayData(){
System.out.println();
System.out.println("Queue Size: " + queue.size());

System.out.println("Queue is empty: " + queue.isEmpty());

System.out.println("----------------------------------------------------");
System.out.println("Display Data using Iterator");
Iterator<Integer> iterator = queue.iterator();
while(iterator.hasNext()) System.out.println(iterator.next());
System.out.println("----------------------------------------------------");
System.out.println();
System.out.println("----------------------------------------------------");
System.out.println("Display Data using for");
for (Integer queueItem : queue) System.out.println(queueItem);
System.out.println("----------------------------------------------------");
}
}



Java - Data Structures - Stack Example

package datastructures.linear;

import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.Stack;

public class StackExample {
public static void main(String[] arg){
StackImplementation obj = new StackImplementation();
obj.addData();
obj.displayData();
obj.operations();
}
}

class StackImplementation{
// Creating an empty Stack
Stack stackObj;
//Creating Integer stack
Stack<Integer> stackSpecificObj = new Stack<>();

public StackImplementation(){
stackObj = new Stack();
}

public void addData(){
//without specifying data type, we can store any type of Data
stackObj.push(5);
stackObj.push("Hello");
stackObj.push(10.5);
stackObj.push(45);
System.out.println(stackObj);

stackSpecificObj.push(12);
stackSpecificObj.push(67);
}

public void operations(){
/*
there are five operations
-------------------------------------------------------------------------------------------------
|Method |Modifier and Type | Method Description |
|-----------------------------------------------------------------------------------------------|
|empty() |boolean | checks the stack is empty or not |
|push(E Item) |E | insert an element on to the top of the stack |
|pop() |E | return top of the stack ( removed item from the stack ) |
|peek() |E | return top of the stack ( without removing ) |
|search(Obj) |int | Search and return the position |
-------------------------------------------------------------------------------------------------
*/
emptyCheck();
insertData(15);
displayData();
popData();
displayData();
peekData();
displayData();
searchData(67);
insertData(11);
insertData(61);
insertData(7);
sortStack();
displayData();

iterateStack();
displayData();
popAllData();
displayData();
popData();
displayData();
peekData();
}

public void searchData(int value){
System.out.println("---------search() Operation ="+value+"------------");
System.out.println(stackSpecificObj.search(value));
}

public void peekData(){
try {
System.out.println("---------peek() Operation------------");
System.out.println(stackSpecificObj.peek());
} catch (EmptyStackException e){
System.err.println("No more Data to peek");
}
}

public void popData(){
try {
System.out.println("---------pop() Operation------------");
System.out.println(stackSpecificObj.pop());
} catch (EmptyStackException e){
System.err.println("No more Data to pop");
}
}

public void insertData(int value){
System.out.println("---------insert(object) Operation------------");
stackSpecificObj.push(value);
}

public void emptyCheck(){
System.out.println("---------empty() Operation------------");
if(stackSpecificObj.empty()){
System.out.println("Stack is Empty");
} else {
System.out.println("Stack isn't Empty");
}
}

public void sortStack(){
System.out.println("---------sort() Operation------------");
stackSpecificObj.sort(null);
}

public void displayData(){
System.out.println("---------Display Stack------------");
System.out.println(stackSpecificObj);
}

public void iterateStack(){
System.out.println("---------Iterate Stack------------");
Iterator it = stackSpecificObj.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

public void popAllData(){
System.out.println("---------pop() Operation for all------------");
while(!stackSpecificObj.empty()){
System.out.println(stackSpecificObj.pop());
}
}
}

Github Link

Java - Data Structures - Multi dimensional Arrays Example

package datastructures.linear;

class MultidimensionalArrays {
public static void main(String[] arg) {
System.out.println("Two Dimensional datastructures.linear.Array Example");
System.out.println("_____________________________");
TwoDimensionalArray obj = new TwoDimensionalArray();
obj.displayArray();
System.out.println("");
System.out.println("Three Dimensional datastructures.linear.Array Example");
System.out.println("_____________________________");
ThreeDimensionalArray objt = new ThreeDimensionalArray();
objt.displayArray();
}
}


class TwoDimensionalArray{
//Declaration an array
private int[][] intArray;

public TwoDimensionalArray(){
//Initializing an array
intArray = new int[][]{{11,24,36,42,58},{45,67,23,45,23},{29,64,73,40,71},{44,66,87,43,95},{34,72,93,37,89}};
}

public void displayArray(){
for(int i=0;i<intArray.length;i++){
for(int j=0;j<intArray[i].length;j++)
System.out.print("["+i+"]["+j+"]'"+intArray[i][j]+"' ");
System.out.println("");
}
}
}

class ThreeDimensionalArray{
//Declaration an array
private long[][][] intArray = new long[5][5][5];

public void assignValues(){
//Initializing an array with random values
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
for(int k=0;k<5;k++)
intArray[i][j][k] = Math.round(Math.random()*100);
}

public void displayArray(){
this.assignValues();
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
for(int k=0;k<5;k++)
System.out.print("["+i+"]["+j+"]["+k+"]'"+intArray[i][j][k]+"' ");
System.out.println("");
}
System.out.println("");
}
}

}

Java - Data Structures - One-Dimensional Array Example

package datastructures.linear;

import java.util.Arrays;

class Array{
public static void main(String arg[]) {
System.out.println("One-Dimensional Arrays Example");
ArraySample obj = new ArraySample();
obj.displayArray();
obj.sortArray();
obj.linearSearch(5);
}
}

class ArraySample{
/*
Declaration an array
_____________________
The declaration can be done using the following both ways
type var-name[];
OR
type[] var-name;
*/
int[] intArray1;
int intArray2[];
String stringArray[];
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
//Object datastructures.linear.Array
Object objectArray[];

//combining both statements (Declaration and Instantiating) in one
int[] intArray = new int[20];

//Defult constructor
public ArraySample(){
/*
Instantiating an datastructures.linear.Array
______________________
var-name = new type [size];
*/
// allocating memory for 5 integers.
intArray1 = new int[5];
stringArray = new String[]{"one","two","three"};

// initialize the first elements of the integer array
intArray1[0] = 6;

// initialize the secound elements of the integer array
intArray1[1] = 2;

// initialize the third elements of the integer array
intArray1[2] = 5;

intArray1[3] = 1;
intArray1[4] = 9;
}

public void sortArray(){
Arrays.sort(intArray1);
System.out.println("---------Sorted datastructures.linear.Array---------");
for (int iterable_element : intArray1) {
System.out.println(iterable_element);
}
}

public void linearSearch(int key){
for (int i = 0; i < intArray1.length; i++)
if(intArray1[i]==key)
System.out.println("Found...! index="+i);
else
System.out.println("Search key not found");

}

public void displayArray(){
//datastructures.linear.Array Length
System.out.println("datastructures.linear.Array size = "+stringArray.length);

// accessing the elements of the specified array
for (int i = 0; i < stringArray.length; i++)
System.out.println("Element at index " + i + " : " + stringArray[i]);


System.out.println("datastructures.linear.Array size = "+intArray1.length);

for (int iterable_element : intArray1) {
System.out.println(iterable_element);
}
}

}

Java - Data Structures - non linear - Binary Tree from the scratch

  package datastructures.linear ; public class TreeFromTheScratch { public static void main (String[] args) { TreeImpl tree = ne...