Provide Best Programming Tutorials

LinkedList In Java

A linked list is implemented using a linked structure.

Nodes

In a linked list, each element is contained in an object, called the node . When a new element is added to the list, a node is created to contain it. Each node is linked to its next neighbor, as shown in Figure below

A node can be created from a class defined as follows:

We use the variable head to refer to the first node in the list, and the variable tail to the last node. If the list is empty, both head and tail are null . Here is an example that creates a linked list to hold three nodes. Each node stores a string element.

Steps:

  1. Declare head and tail.

    Node<String> head = null; //The list is empty now

    Node<String> tail = null;

    head and tail are both null. The list is empty.

  2. Create the first node and append it to the list, as shown in Figure below. After the first node is inserted in the list, head and tail point to this node.

  3. Create the second node and append it into the list, as shown in Figure 24.9a. To append the second node to the list, link the first node with the new node. The new node is now the tail node, so you should move tail to point to this new node, as shown in fixture below

  1. Create the third node and append it to the list, as shown in Figure below. To append the new node to the list, link the last node in the list with the new node. The new node is now the tail node, so you should move tail to point to this new node, as shown in below

    Example

    package LinkedListDemo;
    
    import java.util.LinkedList;
    
    public class LinkedListDemo {
    
        public static void main(String[] args) {
            LinkedList<String> linkedList = new LinkedList<>();
            linkedList.add("Jordan");
            linkedList.add("Kobe");
            linkedList.add("James");
    
            linkedList.add(3,"McGrady");
    
            System.out.println(linkedList);
            System.out.println(linkedList.getLast());
            System.out.println(linkedList.getFirst());
            System.out.println(linkedList.indexOf("Kobe"));
            //Retrieves, but does not remove, the head (first element) of this list.
            System.out.println(linkedList.peek());
            //Adds the specified element as the tail (last element) of this list.
            System.out.println(linkedList.offer("Harden"));
    
            System.out.println(linkedList);
    
            System.out.println(linkedList.peekLast());
            System.out.println(linkedList.getLast());
            System.out.println(linkedList);
    
            //Pops an element from the stack represented by this list.  In other
            //words, removes and returns the first element of this list.
            System.out.println(linkedList.pop());
            System.out.println(linkedList);
    
        }
    }

Leave a Reply

Close Menu