Insert node at the beginning of a Singly Linked List

Insertion in a Singly Linked List 


When using a singly linked list, we can easily insert an element at the beginning of the list, as shown in Figure below. The main idea is that we create a new node, set its next link to refer to the same object as head, and then set head to point to the new node.


Insert at the beginning:

public void insertFirst(int value) {
    Node newNode = new Node(value);
    newNode.next = head; 
    head = newNode;
}


Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*Node of a single linked list of integer */
public class SinglyLinkedList {
	private static Node head; /* instance variable */

	private static class Node {
		private int data; /* we assume data integer */
		private Node next; /* Create a node with the given data and next node */

		public Node(int data) {
			this.data = data;
			this.next = null;
		}
	}

	/* Display single list */
	public void display() {
		Node current = head;
		while (current != null) {
			System.out.print(current.data + " --> ");
			current = current.next;
		}
		System.out.println("null");
	}

	public void insertFirst(int value) {
		Node newNode = new Node(value);

		newNode.next = head;
		head = newNode;
	}

	public static void main(String[] args) {
		SinglyLinkedList s = new SinglyLinkedList();
		s.head = new Node(10);
		Node second = new Node(7);
		Node third = new Node(20);
		Node fourth = new Node(8);
		
		s.head.next = second; // 10 --> 7
		second.next = third; // 10 -->7 -->20
		third.next = fourth; // 10 -->7 -> 20 -->8 -->null
		s.display();
		
		System.out.println("Insert at the beginning:");
		s.insertFirst(4);
		s.display();
	}

}

 

Output:

10 --> 7 --> 20 --> 8 --> null
Insert at the beginning:
4 --> 10 --> 7 --> 20 --> 8 --> null 

Next Post Previous Post
No Comment
Add Comment
comment url