diff --git a/Data Structures/Arrays/C++/Array.cpp b/data_structures/Arrays/C++/Array.cpp similarity index 100% rename from Data Structures/Arrays/C++/Array.cpp rename to data_structures/Arrays/C++/Array.cpp diff --git a/data_structures/Arrays/Java/Array.java b/data_structures/Arrays/Java/Array.java new file mode 100644 index 0000000..7e43178 --- /dev/null +++ b/data_structures/Arrays/Java/Array.java @@ -0,0 +1,102 @@ + +import java.util.Arrays; + +/* + * + /$$$$$$ + /$$__ $$ + | $$ \ $$ /$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$$ + | $$$$$$$$ /$$__ $$ /$$__ $$|____ $$| $$ | $$ /$$_____/ + | $$__ $$| $$ \__/| $$ \__/ /$$$$$$$| $$ | $$| $$$$$$ + | $$ | $$| $$ | $$ /$$__ $$| $$ | $$ \____ $$ + | $$ | $$| $$ | $$ | $$$$$$$| $$$$$$$ /$$$$$$$/ + |__/ |__/|__/ |__/ \_______/ \____ $$|_______/ + /$$ | $$| + | $$$$$$$$/ + \_______/ +*/ +/* + * + + - EXPLANATIONS: + - An array is a data structure that stores a collection of elements of the same data type in a contiguous block of memory. + It provides a way to store and access a group of related values using a single variable name. + + - Each element in an array is identified by an index, which represents its position in the array. + The index starts at 0 for the first element, and increases by 1 for each subsequent element. + This means that if an array has n elements, the indices range from 0 to n-1. + + - Arrays can be used to store and manipulate different types of data, such as numbers, characters, strings, and objects. + They are commonly used in programming for a variety of tasks, such as sorting, searching, and processing large amounts of data. + + - MOST COMMONLY USED BUILT-IN FUNCTIONS: + + - array.append(x) - This function is used to add an element x to the end of the array. + - array.extend(iterable) - This function is used to add the elements of an iterable (such as a list or tuple) to the end of the array. + - array.insert(i, x) - This function is used to insert an element x at a specific index i in the array. + - array.remove(x) - This function is used to remove the first occurrence of element x from the array. + - array.pop(i) - This function is used to remove and return the element at a specific index i in the array. If no index is specified, the last element of the array is removed and returned. + - array.index(x) - This function is used to find the first occurrence of element x in the array and return its index. + - array.count(x) - This function is used to count the number of occurrences of element x in the array. + - array.sort() - This function is used to sort the elements of the array in ascending order. + - array.reverse() - This function is used to reverse the order of the elements in the array. + - len(array) - This function is used to return the number of elements in the array. + + - TIME AND SPACE COMPLEXITY: + + - array.append(x) - Time complexity: O(1), Space complexity: O(1) + - array.extend(iterable) - Time complexity: O(k), where k is the length of the iterable being added, Space complexity: O(k) + - array.insert(i, x) - Time complexity: O(n), where n is the number of elements in the array, Space complexity: O(1) + - array.remove(x) - Time complexity: O(n), where n is the number of elements in the array, Space complexity: O(1) + - array.pop(i) - Time complexity: O(n), where n is the number of elements in the array, Space complexity: O(1) + - array.index(x) - Time complexity: O(n), where n is the number of elements in the array, Space complexity: O(1) + - array.count(x) - Time complexity: O(n), where n is the number of elements in the array, Space complexity: O(1) + - array.sort() - Time complexity: O(n log n), where n is the number of elements in the array, Space complexity: O(1) + - array.reverse() - Time complexity: O(n), where n is the number of elements in the array, Space complexity: O(1) + - len(array) - Time complexity: O(1), Space complexity: O(1) + +*/ + +public class Array{ + public static void main(String[] args) { + + // One Dimensional Array + int[] array1D = {10,22,13,24,1}; + + // Two Dimensional Array + int[][] array2D = {{1, 20, 32, 4}, + {5, 6, 70, 81}, + {9, 10, 7, 12}, + {3, 14, 5, 16}}; + + // Two Dimensional (n x n) Array + int[][] arraynD = {{1,2,3},{4,5,6},{7,8,9}}; + + // initialize new array + int[] newArray = new int[3]; //length = 3 {0,1,2} indexing + + + //Print all the elements of an 1D Array using for each loop + for(int i:array1D){ + System.out.println(i); + } + + System.out.println(); + + //Print all the elements of an 2D Array using for each loop + for(int[] i:array2D){ + for(int j:i){ + System.out.print(j+" "); + } + System.out.println(); + } + + //Array before sorting + System.out.println(Arrays.toString(array1D)); + //To sort an array + Arrays.sort(array1D); + //Array after sorting + System.out.println(Arrays.toString(array1D)); + + } +} diff --git a/Data Structures/Arrays/JavaScript/Array.js b/data_structures/Arrays/JavaScript/Array.js similarity index 100% rename from Data Structures/Arrays/JavaScript/Array.js rename to data_structures/Arrays/JavaScript/Array.js diff --git a/Data Structures/Arrays/Python/Array.py b/data_structures/Arrays/Python/Array.py similarity index 100% rename from Data Structures/Arrays/Python/Array.py rename to data_structures/Arrays/Python/Array.py diff --git a/Data Structures/HashMap/C++/HashMap.cpp b/data_structures/HashMap/C++/HashMap.cpp similarity index 100% rename from Data Structures/HashMap/C++/HashMap.cpp rename to data_structures/HashMap/C++/HashMap.cpp diff --git a/data_structures/HashMap/Java/HashmapJava.java b/data_structures/HashMap/Java/HashmapJava.java new file mode 100644 index 0000000..06db2b8 --- /dev/null +++ b/data_structures/HashMap/Java/HashmapJava.java @@ -0,0 +1,149 @@ +package data_structures.HashMap.Java; + +/* + /$$ /$$ /$$ /$$ /$$ +| $$ | $$ | $$ | $$$ /$$$ +| $$ | $$ /$$$$$$ /$$$$$$$| $$$$$$$ | $$$$ /$$$$ /$$$$$$ /$$$$$$ +| $$$$$$$$ |____ $$ /$$_____/| $$__ $$| $$ $$/$$ $$ |____ $$ /$$__ $$ +| $$__ $$ /$$$$$$$| $$$$$$ | $$ \ $$| $$ $$$| $$ /$$$$$$$| $$ \ $$ +| $$ | $$ /$$__ $$ \____ $$| $$ | $$| $$\ $ | $$ /$$__ $$| $$ | $$ +| $$ | $$| $$$$$$$ /$$$$$$$/| $$ | $$| $$ \/ | $$| $$$$$$$| $$$$$$$/ +|__/ |__/ \_______/|_______/ |__/ |__/|__/ |__/ \_______/| $$____/ + | $$ + | $$ + |__/ +*/ + +/* +### HashMap in Java + + # Definition: +`HashMap` is part of the `java.util` package and implements the `Map` interface. It is used to store key-value pairs, where each key is unique. The `HashMap` class is based on a hash table, providing efficient operations for inserting, deleting, and retrieving elements. + + # Key Characteristics: + +1. Unique Keys : + - Each key in a `HashMap` must be unique. If you try to insert a duplicate key, the new value will replace the old value. + + 2. Null Values : + - `HashMap` allows one null key and multiple null values. + +3. Non-Synchronized : + - `HashMap` is not synchronized, meaning it is not thread-safe. If multiple threads access a `HashMap` concurrently, and at least one of the threads modifies the map, it must be synchronized externally. + +4. Ordering : + - `HashMap` does not guarantee any specific order of the elements. The order of keys and values can change over time. + + # Common Operations: + +1. Creating a HashMap : + ```java + HashMap map = new HashMap<>(); + ``` + +2. Adding Elements : + - Use `put(key, value)` to add key-value pairs. + ```java + map.put(1, "One"); + map.put(2, "Two"); + map.put(3, "Three"); + ``` + +3. Accessing Elements : + - Use `get(key)` to retrieve the value associated with a specific key. + ```java + String value = map.get(2); // Returns "Two" + ``` + +4. Removing Elements : + - Use `remove(key)` to remove a key-value pair. + ```java + map.remove(2); // Removes the key-value pair for key 2 + ``` + +5. Checking if Key or Value Exists : + - Use `containsKey(key)` to check if a key exists. + - Use `containsValue(value)` to check if a value exists. + ```java + boolean hasKey = map.containsKey(1); // Returns true + boolean hasValue = map.containsValue("One"); // Returns true + ``` + +6. Iterating through a HashMap : + - Use `keySet()`, `values()`, or `entrySet()` to iterate through keys, values, or key-value pairs, respectively. + ```java + for (Integer key : map.keySet()) { + System.out.println("Key: " + key); + } + + for (String val : map.values()) { + System.out.println("Value: " + val); + } + + for (Map.Entry entry : map.entrySet()) { + System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); + } + ``` + +7. Getting the Size : + - Use `size()` to get the number of key-value pairs. + ```java + int size = map.size(); // Returns the number of key-value pairs + ``` + +8. Clearing the HashMap : + - Use `clear()` to remove all key-value pairs. + ```java + map.clear(); // Removes all key-value pairs + ``` + +*/ +//java +import java.util.HashMap; +import java.util.Map; + + +public class HashmapJava { + public static void main(String[] args) { + // Creating a HashMap + HashMap map = new HashMap<>(); + + // Adding elements to the HashMap + map.put(1, "One"); + map.put(2, "Two"); + map.put(3, "Three"); + + // Accessing elements + System.out.println("Value for key 2: " + map.get(2)); // Outputs "Two" + + // Removing an element + map.remove(2); + + // Checking if a key or value exists + System.out.println("Contains key 1: " + map.containsKey(1)); // Outputs "true" + System.out.println("Contains value 'One': " + map.containsValue("One")); // Outputs "true" + + // Iterating through the HashMap + System.out.println("Keys:"); + for (Integer key : map.keySet()) { + System.out.println(key); + } + + System.out.println("Values:"); + for (String val : map.values()) { + System.out.println(val); + } + + System.out.println("Key-Value Pairs:"); + for (Map.Entry entry : map.entrySet()) { + System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); + } + + // Getting the size of the HashMap + System.out.println("Size of the map: " + map.size()); + + // Clearing the HashMap + map.clear(); + System.out.println("Size of the map after clear: " + map.size()); + } +} \ No newline at end of file diff --git a/Data Structures/HashMap/Python/HashMap.py b/data_structures/HashMap/Python/HashMap.py similarity index 100% rename from Data Structures/HashMap/Python/HashMap.py rename to data_structures/HashMap/Python/HashMap.py diff --git a/Data Structures/HashSet/C++/HashSet.cpp b/data_structures/HashSet/C++/HashSet.cpp similarity index 100% rename from Data Structures/HashSet/C++/HashSet.cpp rename to data_structures/HashSet/C++/HashSet.cpp diff --git a/data_structures/HashSet/Java/HashSetJava.java b/data_structures/HashSet/Java/HashSetJava.java new file mode 100644 index 0000000..1da1b06 --- /dev/null +++ b/data_structures/HashSet/Java/HashSetJava.java @@ -0,0 +1,130 @@ +package data_structures.HashSet.Java; + +/* + /$$ /$$ /$$ /$$$$$$ /$$ +| $$ | $$ | $$ /$$__ $$ | $$ +| $$ | $$ /$$$$$$ /$$$$$$$| $$$$$$$ | $$ \__/ /$$$$$$ /$$$$$$ +| $$$$$$$$ |____ $$ /$$_____/| $$__ $$| $$$$$$ /$$__ $$|_ $$_/ +| $$__ $$ /$$$$$$$| $$$$$$ | $$ \ $$ \____ $$| $$$$$$$$ | $$ +| $$ | $$ /$$__ $$ \____ $$| $$ | $$ /$$ \ $$| $$_____/ | $$ /$$ +| $$ | $$| $$$$$$$ /$$$$$$$/| $$ | $$| $$$$$$/| $$$$$$$ | $$$$/ +|__/ |__/ \_______/|_______/ |__/ |__/ \______/ \_______/ \___/ +*/ + +/* +### HashSet in Java + + # Definition: +`HashSet` is part of the `java.util` package and implements the `Set` interface. It is used to store a collection of unique elements. `HashSet` is backed by a hash table (actually a `HashMap` instance) and does not guarantee any specific order of the elements. + + # Key Characteristics: + +1. Unique Elements : + - `HashSet` only stores unique elements. If you try to add a duplicate element, the `HashSet` will ignore it. + +2. Null Values : + - `HashSet` allows null values. + +3. Non-Synchronized : + - `HashSet` is not synchronized, meaning it is not thread-safe. If multiple threads access a `HashSet` concurrently, and at least one of the threads modifies the set, it must be synchronized externally. + +4. Ordering : + - `HashSet` does not guarantee any specific order of the elements. The order of elements can change over time. + + # Common Operations: + +1. Creating a HashSet : + ```java + HashSet set = new HashSet<>(); + ``` + +2. Adding Elements : + - Use `add(element)` to add elements to the set. + ```java + set.add("One"); + set.add("Two"); + set.add("Three"); + ``` + +3. Removing Elements : + - Use `remove(element)` to remove a specific element from the set. + ```java + set.remove("Two"); + ``` + +4. Checking if Element Exists : + - Use `contains(element)` to check if an element exists in the set. + ```java + boolean exists = set.contains("One"); // Returns true + ``` + +5. Iterating through a HashSet : + - Use an enhanced for loop or an iterator to iterate through the elements of the set. + ```java + for (String element : set) { + System.out.println(element); + } + + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + ``` + +6. Getting the Size : + - Use `size()` to get the number of elements in the set. + ```java + int size = set.size(); // Returns the number of elements in the set + ``` + +7. Clearing the HashSet : + - Use `clear()` to remove all elements from the set. + ```java + set.clear(); // Removes all elements from the set + ``` + +*/ +//java +import java.util.HashSet; +import java.util.Iterator; + +public class HashSetJava { + public static void main(String[] args) { + // Creating a HashSet + HashSet set = new HashSet<>(); + + // Adding elements to the HashSet + set.add("One"); + set.add("Two"); + set.add("Three"); + + // Adding a duplicate element + set.add("One"); // This will not add a new element + + // Checking if an element exists + System.out.println("Contains 'One': " + set.contains("One")); // Outputs "true" + + // Removing an element + set.remove("Two"); + + // Iterating through the HashSet using an enhanced for loop + System.out.println("Elements in the set:"); + for (String element : set) { + System.out.println(element); + } + + // Iterating through the HashSet using an iterator + System.out.println("Elements in the set (using iterator):"); + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + + // Getting the size of the HashSet + System.out.println("Size of the set: " + set.size()); + + // Clearing the HashSet + set.clear(); + System.out.println("Size of the set after clear: " + set.size()); + } +} \ No newline at end of file diff --git a/Data Structures/HashSet/JavaScript/HashSet.js b/data_structures/HashSet/JavaScript/HashSet.js similarity index 100% rename from Data Structures/HashSet/JavaScript/HashSet.js rename to data_structures/HashSet/JavaScript/HashSet.js diff --git a/Data Structures/HashSet/Python/HashSet.py b/data_structures/HashSet/Python/HashSet.py similarity index 100% rename from Data Structures/HashSet/Python/HashSet.py rename to data_structures/HashSet/Python/HashSet.py diff --git a/Data Structures/Linked List/1. Linked List.cpp b/data_structures/Linked List/CPP/1. Linked List.cpp similarity index 100% rename from Data Structures/Linked List/1. Linked List.cpp rename to data_structures/Linked List/CPP/1. Linked List.cpp diff --git a/data_structures/Linked List/Java/Linkedlist.java b/data_structures/Linked List/Java/Linkedlist.java new file mode 100644 index 0000000..6f956c0 --- /dev/null +++ b/data_structures/Linked List/Java/Linkedlist.java @@ -0,0 +1,161 @@ +package data_structures.Linked List.Java; + +/* + /$$ /$$$$$$ /$$ /$$ /$$ /$$ /$$$$$$$$ /$$$$$$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$$ +| $$ |_ $$_/| $$$ | $$| $$ /$$/| $$_____/| $$__ $$ | $$ |_ $$_/ /$$__ $$|__ $$__/ +| $$ | $$ | $$$$| $$| $$ /$$/ | $$ | $$ \ $$ | $$ | $$ | $$ \__/ | $$ +| $$ | $$ | $$ $$ $$| $$$$$/ | $$$$$ | $$ | $$ | $$ | $$ | $$$$$$ | $$ +| $$ | $$ | $$ $$$$| $$ $$ | $$__/ | $$ | $$ | $$ | $$ \____ $$ | $$ +| $$ | $$ | $$\ $$$| $$\ $$ | $$ | $$ | $$ | $$ | $$ /$$ \ $$ | $$ +| $$$$$$$$ /$$$$$$| $$ \ $$| $$ \ $$| $$$$$$$$| $$$$$$$/ | $$$$$$$$ /$$$$$$| $$$$$$/ | $$ +|________/|______/|__/ \__/|__/ \__/|________/|_______/ |________/|______/ \______/ |__/ + +*/ + + /* +### Explanation: + +1. Node Class : + - Represents a single node in the linked list with `int` data and a reference to the next node. + +2. LinkedList Class : + - Manages the linked list operations: + - `insertAtBeginning(int data)`: Inserts a new node with the specified data at the beginning of the list. + - `insertAtEnd(int data)`: Inserts a new node with the specified data at the end of the list. + - `deleteByKey(int key)`: Deletes the first occurrence of the specified key in the list. + - `display()`: Displays all the elements in the list. + - `size()`: Returns the number of nodes in the list. + - `search(int key)`: Searches for the specified key in the list and returns `true` if found, otherwise `false`. + +3. Main Class : + - Demonstrates the use of the `LinkedList` class by performing various operations like inserting elements, displaying the list, deleting an element, checking the size, and searching for an element. */ + +class Node { + int data; + Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } +} +class LinkedList { + private Node head; + + public LinkedList() { + this.head = null; + } + + // Insert at the beginning + public void insertAtBeginning(int data) { + Node newNode = new Node(data); + newNode.next = head; + head = newNode; + } + + // Insert at the end + public void insertAtEnd(int data) { + Node newNode = new Node(data); + if (head == null) { + head = newNode; + return; + } + Node current = head; + while (current.next != null) { + current = current.next; + } + current.next = newNode; + } + + // Delete by key + public void deleteByKey(int key) { + Node current = head, prev = null; + + // If head node itself holds the key + if (current != null && current.data == key) { + head = current.next; + return; + } + + // Search for the key to be deleted + while (current != null && current.data != key) { + prev = current; + current = current.next; + } + + // If key was not present in linked list + if (current == null) { + return; + } + + // Unlink the node from linked list + prev.next = current.next; + } + + // Display the list + public void display() { + Node current = head; + while (current != null) { + System.out.print(current.data + " -> "); + current = current.next; + } + System.out.println("null"); + } + + // Get the size of the list + public int size() { + int count = 0; + Node current = head; + while (current != null) { + count++; + current = current.next; + } + return count; + } + + // Search for an element + public boolean search(int key) { + Node current = head; + while (current != null) { + if (current.data == key) { + return true; + } + current = current.next; + } + return false; + } +} + +public class Linkedlist { + public static void main(String[] args) { + LinkedList list = new LinkedList(); + + // Insert elements + list.insertAtBeginning(1); + list.insertAtEnd(2); + list.insertAtEnd(3); + list.insertAtEnd(4); + + // Display the list + System.out.println("Linked List:"); + list.display(); + + // Delete an element + list.deleteByKey(3); + + // Display the list + System.out.println("Linked List after deletion:"); + list.display(); + + // Get the size of the list + System.out.println("Size of the linked list: " + list.size()); + + // Search for an element + int searchKey = 2; + if (list.search(searchKey)) { + System.out.println("Element " + searchKey + " is present in the list."); + } else { + System.out.println("Element " + searchKey + " is not present in the list."); + } + } +} \ No newline at end of file diff --git a/Data Structures/Queue/1. Queue.cpp b/data_structures/Queue/CPP/1. Queue.cpp similarity index 100% rename from Data Structures/Queue/1. Queue.cpp rename to data_structures/Queue/CPP/1. Queue.cpp diff --git a/data_structures/Queue/Java/QueueJava.java b/data_structures/Queue/Java/QueueJava.java new file mode 100644 index 0000000..737933d --- /dev/null +++ b/data_structures/Queue/Java/QueueJava.java @@ -0,0 +1,215 @@ +package data_structures.Queue.Java; +/* + /$$$$$$ /$$ /$$ /$$$$$$$$ /$$ /$$ /$$$$$$$$ + /$$__ $$| $$ | $$| $$_____/| $$ | $$| $$_____/ +| $$ \ $$| $$ | $$| $$ | $$ | $$| $$ +| $$ | $$| $$ | $$| $$$$$ | $$ | $$| $$$$$ +| $$ | $$| $$ | $$| $$__/ | $$ | $$| $$__/ +| $$/$$ $$| $$ | $$| $$ | $$ | $$| $$ +| $$$$$$/| $$$$$$/| $$$$$$$$| $$$$$$/| $$$$$$$$ + \____ $$$ \______/ |________/ \______/ |________/ + \__/ +*/ +/* + +} +### Queue in Java + +A `Queue` is a data structure that follows the First In First Out (FIFO) principle, where elements are added to the rear (end) and removed from the front (beginning). + +Java provides the `Queue` interface as part of the `java.util` package. The most commonly used classes that implement the `Queue` interface are `LinkedList` and `PriorityQueue`. + + # Common Operations: + +1. Add Elements : +- `add(E e)` or `offer(E e)`: Inserts the specified element into the queue. The `add` method throws an exception if the element cannot be added, while `offer` returns `false`. + +2. Remove Elements : + - `remove()` or `poll()`: Retrieves and removes the head of the queue. The `remove` method throws an exception if the queue is empty, while `poll` returns `null`. + + 3. Examine Elements : + - `element()` or `peek()`: Retrieves, but does not remove, the head of the queue. The `element` method throws an exception if the queue is empty, while `peek` returns `null`. + +*/ +import java.util.LinkedList; +import java.util.PriorityQueue; +import java.util.Queue; + +public class QueueJava { + public static void main(String[] args) { + Queue queue = new LinkedList<>(); + + // Add elements to the queue + queue.add(1); + queue.add(2); + queue.add(3); + + // Display the queue + System.out.println("Queue: " + queue); + + // Remove elements from the queue + int removedElement = queue.remove(); // Removes the head (1) + System.out.println("Removed Element: " + removedElement); + + // Display the queue + System.out.println("Queue after removal: " + queue); + + // Peek at the head of the queue + int head = queue.peek(); // Retrieves but does not remove the head (2) + System.out.println("Head of the queue: " + head); + + // Display the queue size + System.out.println("Queue size: " + queue.size()); + } +} + + +// Example Using `PriorityQueue` + +class PriorityQueueExample { + public static void main(String[] args) { + Queue priorityQueue = new PriorityQueue<>(); + + // Add elements to the priority queue + priorityQueue.add(5); + priorityQueue.add(1); + priorityQueue.add(3); + + // Display the priority queue + System.out.println("PriorityQueue: " + priorityQueue); + + // Remove elements from the priority queue + int removedElement = priorityQueue.poll(); // Removes the head (1) + System.out.println("Removed Element: " + removedElement); + + // Display the priority queue + System.out.println("PriorityQueue after removal: " + priorityQueue); + + // Peek at the head of the priority queue + int head = priorityQueue.peek(); // Retrieves but does not remove the head (3) + System.out.println("Head of the priority queue: " + head); + + // Display the priority queue size + System.out.println("PriorityQueue size: " + priorityQueue.size()); + + CustomQueue cq = new CustomQueue(); + cq.main2(args); + } +} + +// Implementing a Custom Queue + +class Node { + int data; + Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } +} + +class CustomQueue { + private Node front, rear; + private int size; + + public CustomQueue() { + this.front = this.rear = null; + this.size = 0; + } + + // Add element to the rear + public void enqueue(int data) { + Node newNode = new Node(data); + if (rear == null) { + front = rear = newNode; + } else { + rear.next = newNode; + rear = newNode; + } + size++; + } + + // Remove element from the front + public int dequeue() { + if (front == null) { + throw new IllegalStateException("Queue is empty"); + } + int data = front.data; + front = front.next; + if (front == null) { + rear = null; + } + size--; + return data; + } + + // Peek at the front element + public int peek() { + if (front == null) { + throw new IllegalStateException("Queue is empty"); + } + return front.data; + } + + // Get the size of the queue + public int size() { + return size; + } + + // Check if the queue is empty + public boolean isEmpty() { + return front == null; + } + + // Display the queue + public void display() { + Node current = front; + while (current != null) { + System.out.print(current.data + " -> "); + current = current.next; + } + System.out.println("null"); + } + + public static void main2(String[] args) { + CustomQueue queue = new CustomQueue(); + + // Add elements to the queue + queue.enqueue(10); + queue.enqueue(20); + queue.enqueue(30); + + // Display the queue + System.out.println("Queue:"); + queue.display(); + + // Remove an element from the queue + int removedElement = queue.dequeue(); + System.out.println("Removed Element: " + removedElement); + + // Display the queue + System.out.println("Queue after removal:"); + queue.display(); + + // Peek at the front element + int front = queue.peek(); + System.out.println("Front of the queue: " + front); + + // Display the queue size + System.out.println("Queue size: " + queue.size()); + } +} + +/* + * + ### Explanation: + +1. Using `LinkedList` and `PriorityQueue` : + - Demonstrates the basic operations using Java's built-in `LinkedList` and `PriorityQueue` classes that implement the `Queue` interface. + +2. Custom Queue Implementation : + - Demonstrates how to create a custom queue using a singly linked list. + - Includes methods to add (`enqueue`), remove (`dequeue`), peek, check size, and check if the queue is empty. + - Includes a `main` method to demonstrate usage. + */ \ No newline at end of file diff --git a/Data Structures/Stack/1. Stack.cpp b/data_structures/Stack/CPP/1. Stack.cpp similarity index 100% rename from Data Structures/Stack/1. Stack.cpp rename to data_structures/Stack/CPP/1. Stack.cpp diff --git a/data_structures/Stack/Java/StackJava.java b/data_structures/Stack/Java/StackJava.java new file mode 100644 index 0000000..059851c --- /dev/null +++ b/data_structures/Stack/Java/StackJava.java @@ -0,0 +1,213 @@ +package data_structures.Stack.Java; +/* + /$$$$$$ /$$ /$$ + /$$__ $$ | $$ | $$ +| $$ \__//$$$$$$ /$$$$$$ /$$$$$$$| $$ /$$ +| $$$$$$|_ $$_/ |____ $$ /$$_____/| $$ /$$/ + \____ $$ | $$ /$$$$$$$| $$ | $$$$$$/ + /$$ \ $$ | $$ /$$ /$$__ $$| $$ | $$_ $$ +| $$$$$$/ | $$$$/| $$$$$$$| $$$$$$$| $$ \ $$ + \______/ \___/ \_______/ \_______/|__/ \__/ +*/ + + +/* + * + ### Stack in Java + +A `Stack` is a data structure that follows the Last In First Out (LIFO) principle, where elements are added to and removed from the top of the stack. + +Java provides a `Stack` class as part of the `java.util` package, but it is recommended to use `Deque` (a double-ended queue) for stack operations due to its improved performance and flexibility. + + # Using `Stack` Class: + +1. Basic Operations : + - `push(E item)`: Pushes an item onto the top of the stack. + - `pop()`: Removes and returns the item at the top of the stack. + - `peek()`: Returns the item at the top of the stack without removing it. + - `isEmpty()`: Checks if the stack is empty. + - `search(Object o)`: Returns the 1-based position of the item on the stack. + + # Example Using `Stack` Class: + +```java +import java.util.Stack; + +public class StackExample { + public static void main(String[] args) { + Stack stack = new Stack<>(); + + // Push elements onto the stack + stack.push(1); + stack.push(2); + stack.push(3); + + // Display the stack + System.out.println("Stack: " + stack); + + // Peek at the top element + int topElement = stack.peek(); + System.out.println("Top element: " + topElement); + + // Pop elements from the stack + int removedElement = stack.pop(); + System.out.println("Removed element: " + removedElement); + + // Display the stack + System.out.println("Stack after pop: " + stack); + + // Check if the stack is empty + System.out.println("Is stack empty? " + stack.isEmpty()); + + // Search for an element + int position = stack.search(1); + System.out.println("Position of element 1: " + position); + } + } +``` + + # Using `Deque` for Stack Operations: + +1. Basic Operations : + - `addFirst(E e)`: Pushes an element onto the stack. + - `removeFirst()`: Pops an element from the stack. + - `peekFirst()`: Peeks at the top element of the stack. + - `isEmpty()`: Checks if the stack is empty. + + # Example Using `Deque`: + +*/ +import java.util.ArrayDeque; +import java.util.Deque; + +//DequeStackExample + public class StackJava { + public static void main(String[] args) { + Deque stack = new ArrayDeque<>(); + + // Push elements onto the stack + stack.addFirst(1); + stack.addFirst(2); + stack.addFirst(3); + + // Display the stack + System.out.println("Stack: " + stack); + + // Peek at the top element + int topElement = stack.peekFirst(); + System.out.println("Top element: " + topElement); + + // Pop elements from the stack + int removedElement = stack.removeFirst(); + System.out.println("Removed element: " + removedElement); + + // Display the stack + System.out.println("Stack after pop: " + stack); + + // Check if the stack is empty + System.out.println("Is stack empty? " + stack.isEmpty()); + CustomStack cs = new CustomStack(5); + cs.main2(args); + } +} + +// # Implementing a Custom Stack + + class CustomStack { + private int maxSize; + private int[] stackArray; + private int top; + + public CustomStack(int size) { + maxSize = size; + stackArray = new int[maxSize]; + top = -1; + } + + // Push element onto the stack + public void push(int value) { + if (top == maxSize - 1) { + throw new StackOverflowError("Stack is full"); + } + stackArray[++top] = value; + } + + // Pop element from the stack + public int pop() { + if (isEmpty()) { + throw new IllegalStateException("Stack is empty"); + } + return stackArray[top--]; + } + + // Peek at the top element + public int peek() { + if (isEmpty()) { + throw new IllegalStateException("Stack is empty"); + } + return stackArray[top]; + } + + // Check if the stack is empty + public boolean isEmpty() { + return (top == -1); + } + + // Check if the stack is full + public boolean isFull() { + return (top == maxSize - 1); + } + + // Display the stack + public void display() { + for (int i = 0; i <= top; i++) { + System.out.print(stackArray[i] + " "); + } + System.out.println(); + } + + public static void main2(String[] args) { + CustomStack stack = new CustomStack(5); + + // Push elements onto the stack + stack.push(10); + stack.push(20); + stack.push(30); + + // Display the stack + System.out.println("Stack:"); + stack.display(); + + // Peek at the top element + System.out.println("Top element: " + stack.peek()); + + // Pop elements from the stack + System.out.println("Removed element: " + stack.pop()); + + // Display the stack + System.out.println("Stack after pop:"); + stack.display(); + + // Check if the stack is empty + System.out.println("Is stack empty? " + stack.isEmpty()); + + // Check if the stack is full + System.out.println("Is stack full? " + stack.isFull()); + } +} + +/* + * + ### Explanation: + + 1. Using `Stack` Class : + - Demonstrates the basic stack operations using Java's built-in `Stack` class. + +2. Using `Deque` : + - Demonstrates stack operations using `Deque` for better performance and flexibility. + +3. Custom Stack Implementation : + - Demonstrates how to create a custom stack using an array. + - Includes methods to push, pop, peek, check if the stack is empty or full, and display the stack. + - Includes a `main` method to demonstrate usage. + */ \ No newline at end of file diff --git a/Data Structures/String/C++/String.cpp b/data_structures/String/C++/String.cpp similarity index 100% rename from Data Structures/String/C++/String.cpp rename to data_structures/String/C++/String.cpp diff --git a/data_structures/String/Java/StringJava.java b/data_structures/String/Java/StringJava.java new file mode 100644 index 0000000..9025bbd --- /dev/null +++ b/data_structures/String/Java/StringJava.java @@ -0,0 +1,284 @@ +package data_structures.String.Java; +/* + /$$$$$$ /$$ /$$ + /$$__ $$ | $$ |__/ +| $$ \__//$$$$$$ /$$$$$$ /$$ /$$$$$$$ /$$$$$$ +| $$$$$$|_ $$_/ /$$__ $$| $$| $$__ $$ /$$__ $$ + \____ $$ | $$ | $$ \__/| $$| $$ \ $$| $$ \ $$ + /$$ \ $$ | $$ /$$| $$ | $$| $$ | $$| $$ | $$ +| $$$$$$/ | $$$$/| $$ | $$| $$ | $$| $$$$$$$ + \______/ \___/ |__/ |__/|__/ |__/ \____ $$ + /$$ \ $$ + | $$$$$$/ + \______/ +*/ + + + + + +/* +### Strings in Java + +Strings in Java are objects that represent sequences of characters. The `String` class in Java is used to create and manipulate strings. Strings are immutable, meaning once created, their values cannot be changed. + +#### Creating Strings + +There are several ways to create strings in Java: + +1. String Literal : + ```java + String str1 = "Hello, World!"; + ``` + +2. Using the `new` Keyword : + ```java + String str2 = new String("Hello, World!"); + ``` + +3. From a `char` Array : + ```java + char[] charArray = {'H', 'e', 'l', 'l', 'o'}; + String str3 = new String(charArray); + ``` + +#### Common String Methods + +1. Length : + ```java + int length = str1.length(); + ``` + +2. Character at Specific Index : + ```java + char ch = str1.charAt(0); // 'H' + ``` + + 3. Substring : + ```java + String subStr = str1.substring(0, 5); // "Hello" + ``` + + 4. Contains : + ```java + boolean contains = str1.contains("World"); // true + ``` + +5. Index of Character or Substring : + ```java + int index = str1.indexOf('W'); // 7 + ``` + +6. Last Index of Character or Substring : +```java +int lastIndex = str1.lastIndexOf('o'); // 8 + ``` + +7. Equals : +```java +boolean isEqual = str1.equals("Hello, World!"); // true + ``` + +8. Equals Ignoring Case : + ```java + boolean isEqualIgnoreCase = str1.equalsIgnoreCase("hello, world!"); // true + ``` + + 9. Compare To : + ```java + int compareToResult = str1.compareTo("Hello, World!"); // 0 + ``` + +10. Starts With : + ```java + boolean startsWith = str1.startsWith("Hello"); // true + ``` + +11. Ends With : +```java +boolean endsWith = str1.endsWith("World!"); // true + ``` + + 12. Replace : + ```java + String replacedStr = str1.replace('H', 'h'); // "hello, World!" + ``` + + 13. Trim : + ```java + String strWithSpaces = " Hello, World! "; + String trimmedStr = strWithSpaces.trim(); // "Hello, World!" + ``` + + 14. Split : + ```java + String[] words = str1.split(", "); // ["Hello", "World!"] + ``` + +15. Convert to Uppercase : + ```java + String upperCaseStr = str1.toUpperCase(); // "HELLO, WORLD!" + ``` + + 16. Convert to Lowercase : + ```java + String lowerCaseStr = str1.toLowerCase(); // "hello, world!" + ``` + +17. Concatenate : +```java +String str4 = str1 + " How are you?"; // "Hello, World! How are you?" + String str5 = str1.concat(" How are you?"); // "Hello, World! How are you?" + ``` + + #### StringBuilder and StringBuffer + +For mutable strings, Java provides `StringBuilder` and `StringBuffer`. Both classes are used to create strings that can be modified after creation. + +- StringBuilder : Non-synchronized (not thread-safe), but faster. +- StringBuffer : Synchronized (thread-safe), but slower. + +#### StringBuilder Example + +```java +StringBuilder sb = new StringBuilder("Hello"); +sb.append(", World!"); +String result = sb.toString(); // "Hello, World!" +``` + +#### StringBuffer Example + +```java +StringBuffer sbf = new StringBuffer("Hello"); +sbf.append(", World!"); +String result = sbf.toString(); // "Hello, World!" +``` + +#### String Formatting + +Java provides a way to format strings using the `String.format` method. + +```java +String formattedString = String.format("Hello, %s!", "World"); // "Hello, World!" +``` + +#### Converting Between Strings and Other Data Types + +1. String to Integer : + ```java + int number = Integer.parseInt("123"); + ``` + +2. Integer to String : + ```java + String numberStr = Integer.toString(123); + ``` + +3. String to Double : + ```java + double d = Double.parseDouble("123.45"); + ``` + +4. Double to String : + ```java + String doubleStr = Double.toString(123.45); + ``` + +5. String to Char Array : + ```java + char[] charArray = str1.toCharArray(); + ``` + +6. Char Array to String : + ```java + String strFromArray = new String(charArray); + ``` + +*/ + +public class StringJava { +public static void main(String[] args) { + String str1 = "Hello, World!"; + System.out.println("Original String: " + str1); + + // Length of the string + System.out.println("Length: " + str1.length()); + + // Character at a specific index + System.out.println("Character at index 0: " + str1.charAt(0)); + + // Substring + System.out.println("Substring (0, 5): " + str1.substring(0, 5)); + + // Contains + System.out.println("Contains 'World': " + str1.contains("World")); + + // Index of a character + System.out.println("Index of 'W': " + str1.indexOf('W')); + + // Last index of a character + System.out.println("Last index of 'o': " + str1.lastIndexOf('o')); + + // Equals + System.out.println("Equals 'Hello, World!': " + str1.equals("Hello, World!")); + + // Equals ignoring case + System.out.println("Equals ignoring case 'hello, world!': " + str1.equalsIgnoreCase("hello, world!")); + + // Compare to + System.out.println("Compare to 'Hello, World!': " + str1.compareTo("Hello, World!")); + + // Starts with + System.out.println("Starts with 'Hello': " + str1.startsWith("Hello")); + + // Ends with + System.out.println("Ends with 'World!': " + str1.endsWith("World!")); + + // Replace + System.out.println("Replace 'H' with 'h': " + str1.replace('H', 'h')); + + // Trim + String strWithSpaces = " Hello, World! "; + System.out.println("Trimmed string: '" + strWithSpaces.trim() + "'"); + + // Split + String[] words = str1.split(", "); + System.out.println("Split string: "); + for (String word : words) { + System.out.println(word); + } + + // Convert to uppercase + System.out.println("Uppercase: " + str1.toUpperCase()); + + // Convert to lowercase + System.out.println("Lowercase: " + str1.toLowerCase()); + + // Concatenate + System.out.println("Concatenated string: " + str1.concat(" How are you?")); + + // StringBuilder usage + StringBuilder sb = new StringBuilder("Hello"); + sb.append(", World!"); + System.out.println("StringBuilder result: " + sb.toString()); + + // StringBuffer usage + StringBuffer sbf = new StringBuffer("Hello"); + sbf.append(", World!"); + System.out.println("StringBuffer result: " + sbf.toString()); + + // String formatting + String formattedString = String.format("Hello, %s!", "World"); + System.out.println("Formatted string: " + formattedString); + } +} + +/* +### Explanation: + +- String Creation : Demonstrates various ways to create strings. +- String Methods : Showcases common methods used for string manipulation. +- StringBuilder and StringBuffer : Highlights mutable string classes. +- String Formatting : Shows how to format strings using `String.format`. +- Conversion : Demonstrates how to convert between strings and other data types. +*/ \ No newline at end of file diff --git a/Data Structures/String/JavaScript/String.js b/data_structures/String/JavaScript/String.js similarity index 100% rename from Data Structures/String/JavaScript/String.js rename to data_structures/String/JavaScript/String.js diff --git a/Data Structures/String/Python/String.py b/data_structures/String/Python/String.py similarity index 100% rename from Data Structures/String/Python/String.py rename to data_structures/String/Python/String.py