In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list
public class Linkedlist { Node head; class Node{ int data; Node next; Node(int d){ data =d; next=null; } }
// INSERT THE NODE AT THE BEGIN OF LINKEDLIST.
// INSERT THE NODE AT THE GIVEN POSITION IN LINKEDLIST.public void insertAtfront(int new_data){ // Node temp = head; Node new_node = new Node(new_data); new_node.next = head; head = new_node; }
public void insertAtGiven(Node prev_node,int new_data) { if(prev_node == null){ System.out.print("previous node can't be null"); return; } Node new_node = new Node(new_data); new_node.next = prev_node.next; prev_node.next = new_node; }
// INSERT THE NODE AT THE END OF THE LINKEDLIST.
public void insertAtEnd(int new_data){ Node new_node = new Node(new_data); new_node.next = null; Node last = head; while(last.next!=null){ last = last.next; } last.next= new_node; return; }
// TRAVERSING THE ELEMENT OF LINKEDLIST
public void showlist(){ Node tnode= head; while(tnode!=null){ System.out.print(tnode.data+" "); tnode = tnode.next; } }
// MAIN FUNCTION
public static void main(String ...args) { list.insertAtfront(10); list.insertAtfront(12); list.insertAtfront(14); list.insertAtfront(16); list.insertAtfront(18); list.insertAtfront(19); list.insertAtGiven(12,20); list.insertAtGiven(20,22); list.insertAtEnd(24); list.showlist(); } }