
Linked List in Java
Linked List in Java
- It is based on linear data structure in storage. Not a continuous storage.
- It is implements List and Queue interface in java.
- It store the elements using separate object for address and data part.
- It also returns the element in insertion order.
- It allows null and duplicate elements also.
- It uses the doubly linked list process to store elements
- Doubly linked list having collection of nodes. Such as data node, next node, previous node.
Creating Linked List:
Linked List obj=new Linked List ();
Linked List obj=new Linked List(Collection c);
Methods:
boolean add(E)
E – Element
It is used add a element in last in the list
void add(int,E)
int – index of the element , E –Element
It is used to add element in particular index
void addFirst(E)
E – Element
It is used to add element in first in the list.
void addLast(E)
E – Element
It is used to add element in last in the list.
void offerFirst(E)
E – Element
It is used to add element in front of queue or list.
void offerLast(E)
E – Element
It is used to add element in end of queue or list.
E getFirst()
It is used to get the first element in the list.
E getLast()
It is used to get the last element in the list.
E removeFirst()
It used to remove and returns the first element in the list.
E removeLast()
It used to remove and returns the last element in the list.
E removeFirstOccurence(Object e)
It used to remove and returns the first occurrence of the specified element in list.
E removeLastOccurence(Object e)
It used to remove and returns the last occurrence of the specified element in list.
Example:
public class LinkedListExample { public static void main(String[] args) { LinkedList obj=new LinkedList(); obj.add("hello"); obj.add(1, "hell"); obj.addFirst("welcome"); obj.addLast("world"); obj.offerFirst("happy"); obj.offerLast("sad"); System.out.println("Linked list : " + obj); System.out.println("Get the First Element : " + obj.getFirst()); System.out.println("Get the Last Element : " + obj.getLast()); obj.removeFirst(); System.out.println("Linked list : " + obj); obj.removeLast(); System.out.println("Linked list : " + obj); obj.remove("hell"); System.out.println("Linked list : " + obj); } } |
Linked list : [happy, welcome, hello, hell, world, sad]
Get the First Element : happy Get the Last Element : sad Linked list : [welcome, hello, hell, world, sad] Linked list : [welcome, hello, hell, world] Linked list : [welcome, hello, world] |