Posts

Showing posts from November, 2024

Other queue implementation in java

               A basic queue is a collection of elements with a front end and rear end. Some of the other types of queue’s are listed below. PriorityQueue: A queue with priority value associated with it. It dequeued according to the priority. Generally, higher priority is dequeued first. ArrayDeque : This implementation of queue can be resizable. The elements can be added or removed at both front and back ends. The java implementations of both queues are given below. 1.Priority Queue implementation in java:               This program uses the built in packages java.util.PriorityQueue and java.util.Queue. Steps: ·        Develop a class with main() function. ·        Create an object for Queue class. ·        Insert the data elements to the queue by add() function. · ...

Simple Queue implementation in java

     Queue is a collection of elements stored in sequential manner. It has a principle called FIFO (First In First Out). It means the element added in the queue is removed first.The implementation of queue is done easily using java. The built-in packages in java for implementing queue is given below. java.util.LinkedList java.util.Queue The implementation of simple queue is as follows. It has 5 basic operations. Enqueue : It adds the element to the queue. Dequeue : It removes the element from the queue. Size : It finds the size of the queue. isEmpty : It checks the queue has elements or not. peek() : It finds the front elements. Steps to implement the program: First, include the built-in packages. Create the class   QueueSimple with main () function. An object is created from builtin class “Queue” as integer. Add the elements to the queue by using add() function. Print the elements in the queue. Using the peek () function to print t...

Java implementation of trapping the rainwater using stack

  Trapping the Rainwater is a classical algorithmic problem. It finds the trapping water on the elevation map. Here, the elevation map is implemented by an array as stack. Let us implement this algorithm in Java. First, create an integer array for storing the stack. Each element represents a bar in the elevation map. The bar represents the count of trapping water after the rain. Initialize the two pointers. One points to the left side, and another points to the right side of the array. Find the maximum height of the right and left side of the array and store it in two variables. Finally, calculate the trapped water value by moving the pointers towards the center. It’s time to find the maximum and minimum values from the left and right. Java Implementation public class TrapitRainWater {     public static int trapit(int[] h) {         if (h == null || h.length == 0...

Largest Rectangle in histogram using java

              It is a classic problem in histogram which finds the largest rectangle. The histogram has a collection of integers represented by an array. Each element denotes the height of the bar. Here, a stack is used to implement the largest rectangle in histogram. Let us implement the largest rectangle in histogram. ·        First, create a integer stack for storing the histogram. ·        Declare an integer variable maxiArea and n. ·        Iterate the stack for finding the largest bar in the histogram. ·        If the current bar is greater than the bar in the top of the stack, insert the current value to the stack. ·        Else the value is popped. Check until the last element. ·        Calculate the largest area of the value and display it. Program:...

Valid parenthesis checking using Stack in java

       Let us solve a common problem called “Valid parentheses”. It is a problem which checks a given string has a valid parenthesis. It means that the parentheses are nested and closed properly. If you use stack for solving this problem, it is good to be effective. List of parentheses: ‘(‘ , ’)’ , ’[‘ , ’]’ , ’{‘ , ’}’. Valid usage of parentheses: ‘({[]})’ ‘{[()]}’ ‘[{()}]’ Let us implement this program in java. Program: ·        Create a stack for finding the opening parenthese. ·        Traverse the string character by character. ·        Check for opening parenthesis, if occurs,insert(push) the parenthese into stack. ·        If it is a closing parenthesis, check the stack is having its opening parenthesis. ·        If these two are matching, pop the element from the stack. Otherwise,print the stri...

How to find the Next Greater element in java?

               An array of integers is given. You have to find the next greater element for each element in the array.  This is one of the interview question in java. Let us find the solution for this problem. ·        First, write a class with main function. next, declare an array with some ‘no’ of elements. ·        Create a stack with new object “stack1”. ·        Check the current element of the array with other elements for greater value. If the value is less, then delete the elements.  ·        If the value is greater than the current element, push the current element to stack. otherwise, insert -1 value to stack. ·        Finally, print the value. If stack is null, then there is no greater number. Program: import java.util.Stack; public class NextGElement { ...

The Stock Span Problem in java

     Stocks are everywhere today. This problem deals with stock span calculation for all days. To calculate this, check the stock prices for consecutive days before the day given to you. The logic is to check the stock price on current day with the price on the given day. This problem can be implemented in java as follows. ·        First,use the builtin Stack package. ·        Write a public class spanStockCalc with main() function. ·        Include a function spanCalculate() with an argument sprices as integer. ·        Find the length of the sprices and store it into variable ‘n’. ·        Next,create a integer array with the size of n. ·        A new object is created for stack. ·        Using a for loop, check the two conditions. one is stackis empty or not ...

Stack implementation in java

               Stack is a basic data structure which store the data elements in such a way that LIFO.Stack class is included in java Collections. The built-in package is: java.util.Stack. Logic of stack: LIFO (Last in First Out): The number which is inserted as last will be removed first. Dynamic: The size of stack will be increased or decreased depends on the data. Operations on Stack: push(data) : it is used to add the elements to the stack. pop() : It is used to delete a top most data. peek() : This is used to view the top element of data. search(): It finds a particular data in the stack. empty() :It checks whether stack is empty or not. Java Implementations on Stack Operations:               This java program implements a stack and its operations. It has following steps. Steps: Include the built in java package. A public class is created with main() f...

Josephus problem implementation in java

Finding a solution for a problem is always interesting. Here is the interesting problem called   “Josephus”. What is the Josephus problem? It is a classic game involves a eliminating a person from a group of people who stands in a circle. First, ‘n’ number of people in a circle. Count from a position. At the end of counting, eliminate the person. Continue the process until the person. Java implementation of Josephus problem: It can be done by two ways. ·        Recursive function ·        Iterative method Implementation of Josephus problem using recursive function:   It creates a class “Josephuspbm” with a main() function. A recursive function is created with two member variables. ·        Check this ‘n’ value. If the n is equal to one, then return to 0. Otherwise, call the recursive function. ·        Assign two integer variables with value. On...

Implementation of LinkedList in java

 Linkedlist is a type of data structure which has nodes and pointers. Node a structure which stores data and pointers are used to link the nodes. To implement linkedlist in Java collections framework, we use doubly-linked list. Doubly-linkedlist has two pointers. One points to forward direction and another points to backward direction. Use of doubly-linkedlist: It is dynamic. You can increase the size at runtime.   Insertions and deletions are done in efficient manner. Implementation of Linked List:               This includes the creation of a linked list, adding the elements, displaying the elements, removing a data and iteration. Steps: Include the builtin java packages java.util.LinkedList and java.util.Iterator.   A class “LinkedListSample” is created with main() function. Creation of Linked list : LinkedList is created as String with an object linkList. Inserting the data: Usi...

List interface in java

              It is the fundamental concept of java collections framework. Main purpose of this concept is to traverse the list and its objects. ‘List interface’ – it deals with ordered sequence of elements. If you want to extend this interface for additional methods, just use the ‘Collection’ interface. Collection interface has many methods for searching, traversing, viewing and particular position access. Features: ·        It supports null elements. ·        It deals with ordered collection. ·        Duplicates can be included. ·        Mainly, a particular position is easily accessed. How to implement the “List Interface”?   To implement the list interface, you can use any of the data structure given below. ·        Stack ·        Vector ·  ...

File handling in java

             Files are essentials in software implementation. File handling deals with creation of a file, reading the contents of a file, writing the contents to a file and deleting a file. Built in package in java which supports the file operations is “java.io”. How to implement the file operations in java? There are four operations in file handling listed as follows.  1.      Creating a file  2.      Reading the contents in a file  3.     Writing the contents to a file  4.      Deleting a file 1.Creating a file in java:               It includes the below steps. Steps: Include the builtin packages. Create a   class with main() function. from the File, create a object myFile1. Using the object, call the createNewFile() function. import java.io.File; import java.io.IOException; p...