LinkedList


LinkedList

Linked List is present in the “java.util.package” and a part of Collection Framework. With the help of this class, we can implement Linked List in Java.LinkedList is a linear data structure. The elements are not stored in contiguous locations. They are linked with each other with the help of pointers. Pointers and addresses are used to link the elements. Each element is known as a node. The node contains two parts: the data and the address of the next element. The Linked List is preferred over Arrays due to ease of Insertion and Deletion. While having the advantage of insertion and deletion, a linked list can not be accessed directly. You have to start from the starting node to access any element from the linked list.

We can create a Linked List and do various operations on that:-

  • Adding an element,
  • Changing elements,
  • Deleting element,
  • Iterate the Linked List, etc.

We have constructors in Linked List.

  • We have constructors in Linked List.
  • LinkedList(Collection C)

There are some pre-defined methods in Java Linked List

  • add(int index, E element): Add the element at a specific index.
  • add(E e): Adds to the end of the list.
  • addAll(int index, Collection< E >c): Insert all the elements between the specific position.
  • addFirst(E e): Insert the element at the beginning.
  • addLast(E e): Insert the element at the end of the list.
  • clear(): Removes all elements from the list.
  • clone(): Returns the copy of the Existing Linked List.
  • contains(Object o): Return bool value if o is present in the list.
  • get(int index): Returns the element of the index.
  • getFirst(): Returns the first element
  • offer(E e): Add element at the tail.
  • peek(): Retrieves the elements but does not remove the head of the list.
  • poll(): Retrieves the elements and removes the head.
  • push(E e): Pushes the element into the stack represented by Linked List.
  • remove(): Removes the head.
  • set(int index, E element): Replace the element at position index with the given element).
  • size(): Returns the number of elements.
  • toArray(): Return an array having elements of the Linked List.

Syntax:

Linkedlist object = new Linkedlist();

Example :

Com.knowledge2life import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<String> Web = new LinkedList<String>(); Web.add("Knowledge2life1"); Web.add("Knowledge2life2"); Web.add("Knowledge2life3"); Web.add("Knowledge2life4"); System.out.println(Web); } }

OUTPUT:

[Knowledge2life1, Knowledge2life2, Knowledge2life3, Knowledge2life4]