Adding an Element to the Front of LinkedList in Java
A Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements are linked using pointers and addresses. Each element is known as a node. This article shows how to add an element to the front of LinkedList in Java.
Method 1: (Using user-defined method)
- Allocate the memory to a new node.
- Put in the element to be inserted in the allocated node.
- Make the next of the new node as the head.
- Move the head to point to the new node.
Example:
Java
import java.io.*;
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
public void insertfront( int data)
{
Node new_node = new Node(data);
new_node.next = head;
head = new_node;
}
public void print()
{
Node temp = head;
while (temp != null ) {
System.out.print(temp.data + " " );
temp = temp.next;
}
}
public static void main(String args[])
{
LinkedList l = new LinkedList();
l.insertfront( 6 );
l.insertfront( 5 );
l.insertfront( 8 );
l.insertfront( 9 );
l.print();
}
}
|
Method 2: (Using addFirst(E e) method of LinkedList)
Declaration:
void addFirst(Object element)
Syntax:
LinkedList.addFirst(e)
Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at beginning of the list.
Return Value: This method does not return any value.
Java
import java.util.LinkedList;
class AddElementsAtTheFront {
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
list.addFirst( "HI" );
list.addFirst( "HOW" );
list.addFirst( "ARE" );
list.addFirst( "YOU" );
System.out.print(list);
}
}
|
Output
[YOU, ARE, HOW, HI]
Method 3: (Using offerFirst(E e))
This method also inserts the specified element at the front of the list.
Declaration:
public boolean offerFirst(E e)
Syntax:
LinkedList.offerFirst(e)
Parameters: Here, e is the element to add
Return Value: This method returns true
Example:
Java
import java.util.LinkedList;
class AddingElementsAtTheFront {
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
list.offerFirst( "HI" );
list.offerFirst( "HOW" );
list.offerFirst( "ARE" );
list.offerFirst( "YOU" );
System.out.print(list);
}
}
|
Output
[YOU, ARE, HOW, HI]
Last Updated :
22 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...