Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Linked List Programs in Java

Last Updated on July 1, 2023 by Prepbytes

The LinkedList class of the Java collections framework provides the functionality of the linked list data structure (doubly linked list).

Each element in a linked list is known as a node. It consists of 3 fields:

Prev – stores an address of the previous element in the list. It is null for the first element
Next – stores an address of the next element in the list. It is null for the last element
Data – stores the actual data

Creating a Java LinkedList

Here is how we can create linked lists in Java:

LinkedList linkedList = new LinkedList<>();
Here, Type indicates the type of a linked list. For example,

// create Integer type linked list
LinkedList linkedList = new LinkedList<>();

// create String type linked list
LinkedList linkedList = new LinkedList<>();

Example: Create Linked List Programs in Java

import java.util.LinkedList;

class Main {
  public static void main(String[] args){

    // create linkedlist
    LinkedList<String> animals = new LinkedList<>();

    // Add elements to LinkedList
    animals.add("Dog");
    animals.add("Cat");
    animals.add("Cow");
    System.out.println("LinkedList: " + animals);
  }
}

Output

LinkedList: [Dog, Cat, Cow]

In the above example, we have created a LinkedList named animals.

Here, we have used the add() method to add elements to the LinkedList. We will learn more about the add() method later in this tutorial.

Working of LinkedList in Java

Elements in linked lists are not stored in sequence. Instead, they are scattered and connected through links (Prev and Next).

Here we have 3 elements in a linked list.

Dog – it is the first element that holds null as previous address and the address of Cat as the next address
Cat – it is the second element that holds an address of Dog as the previous address and the address of Cow as the next address
Cow – it is the last element that holds the address of Cat as the previous address and null as the next element

Methods of Java LinkedList

LinkedList provides various methods that allow us to perform different operations in linked lists. We will look at four commonly used LinkedList Operators in this tutorial:

  • Add elements
  • Access elements
  • Change elements
  • Remove elements

Add elements to a LinkedList

We can use the add() method to add an element (node) at the end of the LinkedList. For example,

import java.util.LinkedList;

class Main {
  public static void main(String[] args){
    // create linkedlist
    LinkedList<String> animals = new LinkedList<>();

    // add() method without the index parameter
    animals.add("Dog");
    animals.add("Cat");
    animals.add("Cow");
    System.out.println("LinkedList: " + animals);

    // add() method with the index parameter
    animals.add(1, "Horse");
    System.out.println("Updated LinkedList: " + animals);
  }
}

Output

LinkedList: [Dog, Cat, Cow]
Updated LinkedList: [Dog, Horse, Cat, Cow]

In the above example, we have created a LinkedList named animals. Here, we have used the add() method to add elements to animals.

Notice the statement,

animals.add(1, "Horse");
Here, we have used the index number parameter. It is an optional parameter that specifies the position where the new element is added.

Access LinkedList elements

The get() method of the LinkedList class is used to access an element from the LinkedList. For example,

import java.util.LinkedList;

class Main {
  public static void main(String[] args) {
    LinkedList<String> languages = new LinkedList<>();

    // add elements in the linked list
    languages.add("Python");
    languages.add("Java");
    languages.add("JavaScript");
    System.out.println("LinkedList: " + languages);

    // get the element from the linked list
    String str = languages.get(1);
    System.out.print("Element at index 1: " + str);
  }
}

Output

LinkedList: [Python, Java, JavaScript]
Element at index 1: Java

In the above example, we have used the get() method with parameter 1. Here, the method returns the element at index 1.

We can also access elements of the LinkedList using the iterator() and the listIterator() method.

Change Elements of a LinkedList

The set() method of LinkedList class is used to change elements of the LinkedList. For example,

import java.util.LinkedList;

class Main {
  public static void main(String[] args) {
    LinkedList<String> languages = new LinkedList<>();

    // add elements in the linked list
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    languages.add("Java");
    System.out.println("LinkedList: " + languages);

    // change elements at index 3
    languages.set(3, "Kotlin");
    System.out.println("Updated LinkedList: " + languages);
  }
}

Output

LinkedList: [Java, Python, JavaScript, Java]
Updated LinkedList: [Java, Python, JavaScript, Kotlin]

In the above example, we have created a LinkedList named languages. Notice the line,

languages.set(3, "Kotlin");
Here, the set() method changes the element at index 3 to Kotlin.

Remove element from a LinkedList

The remove() method of the LinkedList class is used to remove an element from the LinkedList. For example,

import java.util.LinkedList;

class Main {
  public static void main(String[] args) {
    LinkedList<String> languages = new LinkedList<>();

    // add elements in LinkedList
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    languages.add("Kotlin");
    System.out.println("LinkedList: " + languages);

    // remove elements from index 1
    String str = languages.remove(1);
    System.out.println("Removed Element: " + str);

    System.out.println("Updated LinkedList: " + languages);
  }
}

Output

LinkedList: [Java, Python, JavaScript, Kotlin]
Removed Element: Python
New LinkedList: [Java, JavaScript, Kotlin]

Here, the remove() method takes the index number as the parameter. And, removes the element specified by the index number.

Other Methods

Methods Description
contains( ) checks if the linkedlist contains the element
indexof( ) returns the index of the first occurrence of the element
lastindexof( ) returns the index of the last occurrence of the elements
clear( ) removes all the elements of the linkedlist
iterator( ) returns an iterator to iterate over linkedlist

Iterating through LinkedList

We can use the Java for-each loop to iterate through LinkedList. For example,

import java.util.LinkedList;

class Main {
    public static void main(String[] args) {
        // Creating a linked list
        LinkedList<String> animals = new LinkedList<>();
        animals.add("Cow");
        animals.add("Cat");
        animals.add("Dog");
        System.out.println("LinkedList: " + animals);

        // Using forEach loop
        System.out.println("Accessing linked list elements:");
        for(String animal: animals) {
            System.out.print(animal);
            System.out.print(", ");
        }
    }
}

Output

LinkedList: [Cow, Cat, Dog]
Accessing linked list elements:
Cow, Cat, Dog, 

LinkedList Vs. ArrayList

Both the Java ArrayList and LinkedList implements the List interface of the Collections framework. However, there exists some difference between them.

LinkedList ArrayList
Implements List, Queue, and Deque interfaces. Implements List Interface.
Stores 3 values (previous address, data, and next address) in a single position. Stores a single value in a single position.
Provides the doubly-linked list implementation. Provides a resizable array implementation.
Whenever an element is added, prev and next addresses are changed. Whenever an element is added, all elements after that position are shifted.
To access an element, we need to iterate from the beginning to the element. Can randomly access elements using indexes.

Conclusion
In conclusion, the backtracking algorithm is a powerful tool for solving a wide range of problems, including linked list programs in Java. By systematically exploring the search space and incrementally building solution candidates, backtracking allows us to find valid solutions, optimize routes, solve puzzles, and more. With its ability to backtrack and undo choices, the algorithm efficiently navigates through complex decision paths, making it applicable to various domains. Whether it’s finding Hamiltonian paths in graphs, solving the N-Queens problem, navigating mazes, or solving the Knight’s Tour problem, backtracking proves its worth. By incorporating backtracking techniques into linked list programs in Java, developers can effectively handle scenarios where multiple paths need to be explored or specific constraints must be satisfied. The versatility and flexibility of the backtracking algorithm make it an invaluable tool in a programmer’s toolkit for developing efficient and robust linked list programs in Java.

Frequently Asked Questions (FAQs)

Q1. How can I use the backtracking algorithm to solve problems involving linked lists in Java?
The backtracking algorithm can be applied to solve problems involving linked lists in Java by formulating the problem as a search space where each decision point represents a node in the linked list. By exploring different paths and backtracking when necessary, you can find valid solutions such as finding a specific element or satisfying certain conditions within the linked list.

Q2. Can the backtracking algorithm be used to solve complex linked list problems efficiently?
The efficiency of the backtracking algorithm in solving complex linked list problems depends on the size of the search space and the specific constraints involved. While backtracking explores all possible solutions, it may become resource-intensive for large linked lists. In such cases, optimizing techniques like pruning or heuristics can be employed to reduce the search space and improve efficiency.

Q3. What are some common examples of linked list programs in Java that can be solved using backtracking?
Some common examples of linked list programs in Java that can be solved using backtracking include finding a specific element in the linked list, detecting cycles or loops in the list, determining whether the list is a palindrome, or finding combinations of elements that satisfy certain conditions within the list.

Q4. Are there any limitations to using the backtracking algorithm for linked list programs in Java?
While the backtracking algorithm is a powerful technique, it may not be suitable for all linked list problems. Its effectiveness depends on the nature of the problem and the complexity of the search space. Problems with a large number of elements or complex constraints may require alternative algorithms or data structures for more efficient solutions.

Q5. Can the backtracking algorithm be used for linked lists with nested structures or multiple levels?
Yes, the backtracking algorithm can be adapted to handle linked lists with nested structures or multiple levels. By appropriately defining the decision points and constraints, the algorithm can explore all possible combinations within the linked list, considering nested elements or levels as additional dimensions in the search space.

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java

Leave a Reply

Your email address will not be published. Required fields are marked *