Search

Thursday, July 9, 2015

How to add element at first and last position of linked list in Java?

LinkedList class in java.util package provides addFirst() method to add an element at the start of the linked list (also known as head)  and addLast() method to add an element at the end of the linked list, also known as tail of the linked list. Java's LinkedList class is an implementation of doubly linked list data structure but it also implement java.util.Deque interface and these two methods came from that interface, which means they are only available from Java 1.6 onward. addFirst() method insert the specified element at the beginning of the linked list and addLast() method insert the specified element at the end of the linked list. LinkedList class is good if your program requires you to frequently add and remove element than searching for element because it provides O(1) performance for adding and removing element at start and end of the linked list but O(n) for searching an element in the list, because you need to traverse whole list to find the specified element. If you are serious about learning Java collection framework in detail than I suggest you to take a loot at Java Generics and Collection book by Maurice Naftalin. Its one of the best book to master Java collection framework and quite useful from both learning and interview point of view.
Read more »

No comments:

Post a Comment