Linked List Example In Java

This section will help you to understand LinkedList in Java. How to create LinkedList, how to Add element in LinkedList, how to Remove element from the LinkedList etc.

Linked List Example In Java

LikedList implements List interface which perform all operation  like add, remove, delete etc. LinkedList class provide  method to insert, remove , to get the element, insert at the beginning. These operation allow linkedList to use as stack, queue, dequeue. This class can implement dequeue interface which provide first in first out, for add, remove along with other stack operation. The operation which perform adding or removing element will traverse the element from beginning and end of the list.

LinkedList has following constructor:

  • LinkedList() : Create a empty linked list.
  • LinkedList(Collection c) : Create a linked list which initialize the element from collection.

LinkedList class define some useful method which manipulate and access the element.

Some of the element of linked list are as follows:

  • void addFirst(Object ob) : Add element to the beginning of the list.
  • void addLast(Object ob) : Add element at the last of the list.
  • Object getFirst() : To get the first element.
  • Object getLast() : To get the last element.
  • Object removeFirst():  To remove the first element from the List.
  • Object removeLast() : To remove the last element from the List.

The following program will illustrate the LinkedList example

import java.util.*;
public class LinkedListDemo {
	public static void main(String args[])
		LinkedList list = new LinkedList();
		// add elements to the linked list
		list.add(1, "A2");
		System.out.println("Original contents of list: " + list);
		// remove elements from the linked list
		System.out.println("Contents of list after deletion: "+ list);
		// remove first and last elements
		System.out.println("list after deleting first and last: "+ list);
		// get and set a value
		System.out.println("list after change: " + list);

Output from the program:

Download Source Code