Linked List - Introduction and Insertion

Introduction:
    Linked list is a linear data structure. It consists of nodes. Each node has data and pointer to the next node. Linked list is represented by it's head pointer.


Representation of a node:


class Node
{
      int data;
      //reference to the next node
      Node next;

      //constructor to initialize the node
      Node(int data){
          this.data = data;
          next = null;
      }
}



Insertion :

(i) insertion at the head of the linked list:

Steps:
1) Create a node with given data.
2) Make the next of the node to point to head , so that we are preserving the pointer to next node.
3) Make the head to point to new node.

Code:

void Insert(Node head,int data) {
    Node newNode = new Node(data);
    newNode.next = head;
    head = newNode;
}

Illustration:

Insertion of 1 at the head of the list 2->3->4
    

(ii) Insertion of a node after a given node:

Steps:
1) Create a new node with given data.
2) Make the next of the new node to point to present node's next.
3) Make the next of the present node to point to new node.

Code:

void insert(Node presentNode, int data){
     Node newNode = new Node(data);
     newNode.next = presentNode.next;
     presentNode.next = newNode;
}

Illustration:

Insert 2 after 3 in the list 1->3->4


(iii) Insertion of a node at the end:

Steps:
1) Traverse the list till you reach the last node. ( a last node is one whose next pointer is null)
2) Insert new node at the next of the last node.

Code:

Node Insert(Node head,int data) {

    Node newNode = new Node(data);

    Node last = head;
    
    while(last.next!=null){
        last = last.next;
        
    }

    last.next = newNode;
    
    return head;

}

Illustration:

Insert 4 at the end of the list 1->2->3



      

      

Comments

Popular posts from this blog

Tree traversals - Inorder Traversal

Binary Search tree (Insertion)

Stack implementation using array