Thursday, July 18, 2024

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This algorithm uses two pointers, a slow pointer and a fast pointer. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. When the fast pointer reaches the end of the list, the slow pointer will be at the middle. Here's how you can implement it:

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class LinkedList {
    Node head;

    // Function to add a new node at the end
    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // Function to find the middle node
    public Node findMiddle() {
        if (head == null) {
            return null;
        }

        Node slowPointer = head;
        Node fastPointer = head;

        while (fastPointer != null && fastPointer.next != null) {
            slowPointer = slowPointer.next;
            fastPointer = fastPointer.next.next;
        }

        return slowPointer;
    }

    // Function to print the LinkedList
    public void printList() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        list.printList();

        Node middle = list.findMiddle();
        if (middle != null) {
            System.out.println("The middle element is: " + middle.data);
        } else {
            System.out.println("The list is empty.");
        }
    }
}
Explanation:
Node Class: This is a simple class representing a node in the linked list.
LinkedList Class: This class contains methods to add a node, find the middle node, and print the linked list.
add Method: This method adds a new node to the end of the linked list.
findMiddle Method: This method uses the tortoise and hare algorithm to find the middle node. If the list is empty, it returns null.
printList Method: This method prints all the elements of the linked list.
main Method: This is the entry point of the program, where we create a linked list, add elements to it, print the list, and find and print the middle element.

Thursday, August 5, 2021

How to sort an HashMap based on value

 
 

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortHashMapByValue {

	public static void main(String[] args) {

		HashMap<String,Integer> unsortMap = new HashMap<String, Integer>();
		unsortMap.put("Ram", 10);
		unsortMap.put("Syam", 50);
		unsortMap.put("Radhe", 5);
		unsortMap.put("Krishna", 80);
		unsortMap.put("Suneel", 20);
		
		System.out.println("Before sorting:");
		printMap(unsortMap);
        
		System.out.println("\n");
		System.out.println("Sorting sorting:");
		HashMap<String,Integer> sortedMap = (sortHashMap(unsortMap));
		printMap(sortedMap);
		
	}

	private static HashMap<String, Integer> sortHashMap(HashMap<String, Integer> unsortMap) {
		List<Entry<String, Integer>> list = new LinkedList<Map.Entry<String,Integer>>(unsortMap.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {

			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for (Entry<String, Integer> entry : list) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		return sortedMap;
	}

	private static void printMap(HashMap<String, Integer> unsortMap) {
		
		for(Entry<String, Integer> entry : unsortMap.entrySet()) {
			
			System.out.println("The Key is :- "+entry.getKey()+" The Value is:- "+entry.getValue());
		}
	}

}

Output:-

Before sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Krishna The Value is:- 80 The Key is :- Syam The Value is:- 50 The Key is :- Suneel The Value is:- 20 The Key is :- Ram The Value is:- 10 Sorting sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Ram The Value is:- 10 The Key is :- Suneel The Value is:- 20 The Key is :- Syam The Value is:- 50 The Key is :- Krishna The Value is:- 80

How to reverse linked list without using inbuild function or extra loop

  
import java.util.LinkedList;

public class LinkedListReversePractice {

	public static void main(String[] args) {

		LinkedList<Integer> numbers = new LinkedList<Integer>();
		numbers.add(1);
		numbers.add(2);
		numbers.add(3);
		numbers.add(4);
		numbers.add(5);
		
		System.out.println("LinkedList before reversion:- "+numbers);
		
		numbers = reverseLinkedList(numbers);
		System.out.println("LinkedList after reversion:- "+numbers);
		
	}

	private static LinkedList<Integer> reverseLinkedList(LinkedList<Integer> numbers) {
		
		for(int i = 0; i< numbers.size()/2; i++) {
			 
			int temp = numbers.get(i);
			numbers.set(i, numbers.get(numbers.size()-1-i));
			numbers.set(numbers.size()-1-i, temp);
			
		}
		return numbers;
	}
	
}

Output:-

LinkedList before reversion:- [1, 2, 3, 4, 5] LinkedList after reversion:- [5, 4, 3, 2, 1]

How to find prime numbers from 1 to 100


public class PrimeNumber1To100 {

	public static void main(String[] args) {

		System.out.println("Prime numbers from 1 to 100 are :");

		for(int i=1;i<=100;i++) {
			
			int counter=0;
			for(int num = i;num>=1;num--) {
				
				if(i%num == 0) {
					
					counter++;
				}
			}
			if(counter == 2) {
				System.out.print(i+" ");
			}
		}
	}

}

Output:-

Prime numbers from 1 to 100 are : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Least repeated Item in the Integer Array

  
  
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class LeastRepeatedNumber {

	public static void main(String[] args) {

		int[] array1 = {1,1,3,2,3,1,4,2,2};
		System.out.println("Least Repeated Number is : "+findLeastRepatedNumber(array1));

	}
	public static Integer findLeastRepatedNumber(int ...array) {
		Integer leastRepatedCount=0;
		Map<nteger,Integer> map = new HashMap<>();
		Integer leastRepeatedItem=null;
		for(int i:array) {

			if(map.containsKey(i)) {
				int counter = map.get(i)+1;
				map.put(i, counter);
			}else {
				map.put(i,1);
			}

		}

		for(Entry<Integer, Integer> entry : map.entrySet()) {

			int v = entry.getValue();
			int k = entry.getKey();
			if(v>1) {

				if(leastRepatedCount==0 || v<leastRepatedCount) {
					leastRepatedCount = v;
					leastRepeatedItem = k;
				}

			}

		}
		return leastRepeatedItem;
	}
}


Output:-

Least Repeated Number is : 3

Thursday, March 18, 2021

Common elements in two sorted arrays



import java.util.ArrayList;
import java.util.Arrays;

public class CommonNumbers {

	public static void main(String[] args) {
          int[] array1A = {1, 3, 4, 6, 7, 9};
          int[] array2A = {1, 2, 4, 5, 9, 10};
          Integer[] com = common(array1A,array2A);
          for(int i : com) {
              System.out.println(i);
          }

	}

	public static Integer[] common(int array1[], int array2[]) {
		
		int p1=0,p2=0;
		ArrayList<Integer> list = new ArrayList<>();
		while(p1<array1.length && p2 < array2.length) {
			
			if(array1[p1]  == array2[p2]) {
				list.add(array1[p1]);
				p1++;
				p2++;
			}else if(array1[p1] > array2[p2]) {
				p2++;
			}else {
				p1++;
			}
		}
		Integer[] common = new Integer[list.size()];
		return list.toArray(common);
	}
}

Output:-

1 4 9

Wednesday, March 17, 2021

How to find pair of two numbers that's multiply equals to Key

  

    import java.util.ArrayList;

    public class FindPair {

        public static void main(String[] args) {
            int arr[] = {1,2,4,6,3,5}; 
            int key = 20; 
            findPair(arr,key);


        }

        private static void findPair(int[] arr, int key) {
            ArrayList<Integer> numbers = new ArrayList<>();
            boolean status = false;
            for(int num : arr) {

                int anotherNumber = (key/num);
                if(numbers.contains(anotherNumber) && (anotherNumber*num) == key) {
                    status=true;
                    System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
                }
                numbers.add(num);
            }
            if(!status)
                System.out.print("No such pair"); 

        }

    }

Output:-

Pair Found:- (4,5)

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...