Searching for a node in Linked List

Searching for a node in Linked List
Given a node data, we will find the position of the node in the list if present counting from 0.
As we know the last node's next points to null, we will loop the list till the next of node points to null and check each node data with the given node's data.

Below is a Java code to find the position of a node.


private void searchNode(LinkedNode node2) {
 int position = 0;
 if(head == null){
            System.out.println("List is empty");
            return;
        }
        if(head.value == node2.value){
            System.out.println("Node found a position " + position);
            return;
        }else{
            
            LinkedNode temp = head;
            while(temp != null && temp.value != node2.value ){
  position++;
                temp = temp.next;
            }
            if(temp == null){
                System.out.println("Node found a position " + position);
            }else{
                temp1.next = temp.next;
            }
        }
 }

Hope you like it. Please comment for doubts.
Happy Learning !!!
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment