LinkedList in Java

Posted on Updated on

LinkedList extends AbstractSequentialList and implements the List interface. This provides a linked-list data structure. To help you understand better, see the graphical representation of data structure-

LinkedList

LinkedList has two constructor:

  1. LinkedList() : This will create an empty LinkedList list.
  2. LinkedList(Collection c) : This will create an LinkedList list with elements of Collection c.

In addition to methods defined by Collection and List, LinkedList has defined some methods for accessing and modifying its data. Let’s see them one by one:

  1. void addFirst(Object obj): This will add object obj at the first position of LinkedList.
  2. void addLast(Object obj): This will add object obj at the last position of LinkedList.
  3. Object removeFirst(): This will remove element from the first position.
  4. Object removeLast(): This will remove element from the last position.
  5. Object getFirst(): This will fetch element at first position from the LinkedList.
  6. Object getLast(): This will fetch element at last position from the LinkedList.

Let us see an example to understand better:

OUTPUT:

LinkedList after adding elements [1, 2, 3, 4]
LinkedList after adding element to first position [12, 1, 2, 3, 4]
LinkedList after adding element to last position [12, 1, 2, 3, 4, 13]
LinkedList after removing element from first position [1, 2, 3, 4, 13]
LinkedList after removing element from last position [1, 2, 3, 4]
LinkedList after removing element from specified index [1, 2, 3]
First element of LinkedList: 1
Last element of LinkedList: 3

It clear from this example, how methods discussed above are working on any LinkedList.

Apart from the methods discussed, the methods defined in List is also applicable for LinkedList, since definition of LinkedList say- it implements List.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.