Insert a Node at a Specific Position in a Linked List
A new element is inserted at the given specified position in the singly linked list. For example - if the given List is 10->7->20->5 and a new value 8 is added at position 3, the Linked List becomes 10->7->8->20->5.
Example: Insert a Node Position :3 and value: 8
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 57 58 59 60 61 62 63 64 65 | /*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 insert(int position, int value) { Node newnode = new Node(value); if(position ==1) { newnode.next = head; head = newnode; }else { Node previous = head; int count = 1; while(count< position - 1 ) { previous = previous.next; count++; } Node current = previous.next; previous.next = newnode; newnode.next = current; } }
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(5); s.head.next = second; // 10 --> 7 second.next = third; // 10 -->7 -->20 third.next = fourth; // 10 -->7 -> 20 -->5 -->null System.out.println("Before Singly linked list:"); s.display(); System.out.println("Linked list after insertion at position 3 and value 8:"); s.insert(3, 8); s.display(); }
}
|
Output:
Before Singly linked list:
10 --> 7 --> 20 --> 5 --> null
Linked list after insertion at position 3 and value 8:
10 --> 7 --> 8 --> 20 --> 5 --> null