Add a node at the end of a Singly Linked List

We will see how to add a node at the end of a Singly Linked List.
Basically, a new node will be added after the last node of the given Singly Linked List. First, we will check whether the given linked list is empty or not, if the linked list is empty that means there is no node in the linked list. As a result of make the new node as the head. Otherwise, given Linked List is 10->7->20->8->null and we add a new node 15 at the end of the Singly Linked List, new node will be added after 8 because 8 points to the null which means there is no node left in the Singly Linked List. Then the Singly Linked List would be 10->7->20->8->15->null.


	public void insertEnd(int value) {
		Node newNode = new Node(value);
		if(head==null) {
			head = newNode;
			return;
		}
		Node current = head;
		while(current.next!=null) {
			current = current.next;
		}
		current.next = newNode;
	}



Java Code

 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
50
51
52
53
54
55
56
/*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 the single linked list */
	public void display() {
		Node current = head;
		while (current != null) {
			System.out.print(current.data + " --> ");
			current = current.next;
		}
		System.out.println("null");
	}
	//Add a node at the end of a Singly Linked List
	public void insertEnd(int value) {
		Node newNode = new Node(value);
		if(head==null) {
			head = newNode;
			return;
		}
		Node current = head;
		while(current.next!=null) {
			current = current.next;
		}
		current.next = 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
		System.out.println("Before Insert:");
		s.display();
		
		System.out.println("After Insert:");
		s.insertEnd(15); // 10 -->7 --> 20 -->8 -->15 -->null
		s.display();
	}

}

Output

Before Insert:
10 --> 7 --> 20 --> 8 --> null
After Insert:
10 --> 7 --> 20 --> 8 --> 15 --> null

You may also like...
Singly Linked Lists
Insert node at the beginning of a Singly Linked List
Insert a Node at a Specific Position in a Linked List
Find length of a Singly Linked List

Next Post Previous Post