TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Program To Search An Element In A Singly Linked List

Program To Search An Element In A Singly Linked List on fibonacci, factorial, prime, armstrong, swap, reverse, search, sort, stack, queue, array, linkedlist, tree, graph etc.

<< Back to PROGRAM

Program to search an element in a singly linked list

Explanation

In this program, we need to search a node in the given singly linked list.

Program to search an element in a singly linked list

To solve this problem, we will traverse through the list using a node current. Current points to head and start comparing searched node data with current node data. If they are equal, set the flag to true and print the message along with the position of the searched node.

For, eg. In the above list, a search node says 4 which can be found at the position 4.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class SearchLinkedList which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail's next will point to a newly added node. This new node will become the new tail of the list.
  4. searchNode() will search for a node in the list:
    1. Variable i will keep track of the position of the searched node.
    2. The variable flag will store boolean value false.
    3. Node current will point to head node.
    4. Iterate through the loop by incrementing current to current.next and i to i + 1.
    5. Compare each node's data with the searched node. If a match is found, set flag to true.
    6. If the flag is true, display the position of the searched node.
    7. Else, display the message "Element is not present in the list".
  5. display() will display the nodes present in the list:
    1. Define a node current which will initially point to head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

#Represent a node of the singly linked list
class Node:
    def __init__(self,data):
        self.data = data;
        self.next = None;
        
class SearchLinkedList:
    #Represent the head and tail of the singly linked list
    def __init__(self):
        self.head = None;
        self.tail = None;
        
    #addNode() will add a new node to the list
    def addNode(self, data):
        #Create a new node
        newNode = Node(data);
        
        #Checks if the list is empty
        if(self.head == None):
            #If list is empty, both head and tail will point to new node
            self.head = newNode;
            self.tail = newNode;
        else:
            #newNode will be added after tail such that tail's next will point to newNode
            self.tail.next = newNode;
            #newNode will become new tail of the list
            self.tail = newNode;
            
    #searchNode() will search for a given node in the list
    def searchNode(self, data):
        current = self.head;
        i = 1;
        flag = False;
        
        #Checks whether list is empty
        if(self.head == None):
            print("List is empty");
        else:
            while(current != None):
                #Compares node to be found with each node present in the list
                if(current.data == data):
                    flag = True;
                    break;
                i=i+1;
                current = current.next;
        if(flag):
            print("Element is present in the list at the position : " + str(i));
        else:
            print("Element is not present in the list");
 
sList = SearchLinkedList();
 
#Add nodes to the list
sList.addNode(1);
sList.addNode(2);
sList.addNode(3);
sList.addNode(4);
 
#Search for node 2 in the list
sList.searchNode(2);
#Search for the node  in the list
sList.searchNode(7);

Output:

Element is present in the list at the position : 2
Element is not present in the list

C

#include <stdio.h>
#include <stdbool.h>
 
//Represent a node of the singly linked list
struct node{
    int data;
    struct node *next;
};    
 
//Represent the head and tail of the singly linked list
struct node *head, *tail = NULL;
 
//addNode() will add a new node to the list
void addNode(int data) {
    //Create a new node
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = NULL;
    
    //Checks if the list is empty
    if(head == NULL) {
        //If list is empty, both head and tail will point to new node
        head = newNode;
        tail = newNode;
    }
    else {
        //newNode will be added after tail such that tail's next will point to newNode
        tail->next = newNode;
        //newNode will become new tail of the list
        tail = newNode;
    }
}
 
//searchNode() will search for a given node in the list
void searchNode(int data) {
    struct node *current = head;
    int i = 1;
    bool flag = false;
    
    //Checks whether list is empty
    if(head == NULL) {
        printf("List is empty \n");
    }
    else {
        while(current != NULL) {
             //Compares node to be found with each node present in the list
            if(current->data == data) {
                flag = true;
                break;
            }
            i++;
            current = current->next;
        }
    }
    if(flag)
         printf("Element is present in the list at the position: %d\n", i);
    else
         printf("Element is not present in the list\n");
}
    
int main()
{
    //Add nodes to the list
    addNode(1);
    addNode(2);
    addNode(3);
    addNode(4);
    
    //Search for node 2 in the list
    searchNode(2);
    //Search for node  in the list
    searchNode(7);
        
    return 0;
}

Output:

Element is present in the list at the position : 2
Element is not present in the list

JAVA

public class SearchLinkedList {
    
    //Represent a node of singly linked list
    class Node{
        int data;
        Node next;
        
        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
 
    //Represent the head and tail of the singly linked list
    public Node head = null;
    public Node tail = null;
    
    //addNode() will add a new node to the list
    public void addNode(int data) {
        //Create a new node
        Node newNode = new Node(data);
        
        //Checks if the list is empty
        if(head == null) {
            //If list is empty, both head and tail will point to new node
            head = newNode;
            tail = newNode;
        }
        else {
            //newNode will be added after tail such that tail's next will point to newNode
            tail.next = newNode;
            //newNode will become new tail of the list
            tail = newNode;
        }
    }
    
    //searchNode() will search for a given node in the list
    public void searchNode(int data) {
        Node current = head;
        int i = 1;
        boolean flag = false;
        
        //Checks whether list is empty
        if(head == null) {
            System.out.println("List is empty");
        }
        else {
            while(current != null) {
                 //Compares node to be found with each node present in the list
                if(current.data == data) {
                    flag = true;
                    break;
                }
                i++;
                current = current.next;
            }
        }
        if(flag)
             System.out.println("Element is present in the list at the position : " + i);
        else
             System.out.println("Element is not present in the list");
    }
    
    public static void main(String[] args) {
        
        SearchLinkedList sList = new SearchLinkedList();
        
        //Add nodes to the list
        sList.addNode(1);
        sList.addNode(2);
        sList.addNode(3);
        sList.addNode(4);
        
        //Search for node 2 in the list
        sList.searchNode(2);
        //Search for a node  in the list
        sList.searchNode(7);
    }
}

Output:

Element is present in the list at the position : 2
Element is not present in the list

C#

using System;
                    
public class CreateList
{
    //Represent a node of singly linked list
    public class Node<T>{
        public T data;
        public Node<T> next;
        
        public Node(T value) {
            data = value;
            next = null;
        }
    }
        
    public class SearchLinkedList<T>{
        //Represent the head and tail of the singly linked list
        public Node<T> head = null;             
         public Node<T> tail = null;
    
        //addNode() will add a new node to the list
        public void addNode(T data) {
            //Create a new node
            Node<T> newNode = new Node<T>(data);
 
            //Checks if the list is empty
            if(head == null) {
                //If list is empty, both head and tail will point to new node
                head = newNode;
                tail = newNode;
            }
            else {
                //newNode will be added after tail such that tail's next will point to newNode
                tail.next = newNode;
                //newNode will become new tail of the list
                tail = newNode;
            }
        }
    
        //searchNode() will search for a given node in the list
        public void searchNode(T data) {
            Node<T> current = head;
            int i = 1;
            Boolean flag = false;
 
            //Checks whether list is empty
            if(head == null) {
                Console.WriteLine("List is empty");
            }
            else {
                while(current != null) {
                     //Compares node to be found with each node present in the list
                    if(current.data.Equals(data)) {
                        flag = true;
                        break;
                    }
                    i++;
                    current = current.next;
                }
            }
            if(flag)
                 Console.WriteLine("Element is present in the list at the position : " + i);
            else
                 Console.WriteLine("Element is not present in the list");
        }
    }
    
    public static void Main()
    {
        SearchLinkedList<int> sList = new SearchLinkedList<int>();
        
        //Add nodes to the list
        sList.addNode(1);
        sList.addNode(2);
        sList.addNode(3);
        sList.addNode(4);
        
        //Search for node 2 in the list
        sList.searchNode(2);
        //Search for a node  in the list
        sList.searchNode(7);
    }
}

Output:

Element is present in the list at the position : 2
Element is not present in the list

PHP

<!DOCTYPE html>
<html>
<body>
<?php
//Represent a node of singly linked list
class Node{
    public $data;
    public $next;
    
    function __construct($data){
        $this->data = $data;
        $this->next = NULL;
    }
}
class SearchLinkedList{
    //Represent the head and tail of the singly linked list
    public $head;
    public $tail;
    function __construct(){
        $this->head = NULL;
        $this->tail = NULL;
    }
    
    //addNode() will add a new node to the list
    function addNode($data) {
        //Create a new node
        $newNode = new Node($data);
        
        //Checks if the list is empty
        if($this->head == NULL) {
            //If list is empty, both head and tail will point to new node
            $this->head = $newNode;
            $this->tail = $newNode;
        }
        else {
            //newNode will be added after tail such that tail's next will point to newNode
            $this->tail->next = $newNode;
            //newNode will become new tail of the list
            $this->tail = $newNode;
        }
    }
    
    //searchNode() will search for a given node in the list
    function searchNode($data) {
        $current = $this->head;
        $i = 1;
        $flag = false;
        
        //Checks whether list is empty
        if($this->head == null) {
            print("List is empty<br>");
        }
        else {
            while($current != null) {
                 //Compares node to be found with each node present in the list
                if($current->data == $data) {
                    $flag = true;
                    break;
                }
                $i++;
                $current = $current->next;
            }
        }
        if($flag)
             print("Element is present in the list at the position : " . $i);
        else
             print("<br>Element is not present in the list");
    }
}
    
$sList = new SearchLinkedList();
        
//Add nodes to the list
$sList->addNode(1);
$sList->addNode(2);
$sList->addNode(3);
$sList->addNode(4);
 
//Search for node 2 in the list
$sList->searchNode(2);
//Search for node  in the list
$sList->searchNode(7);
?>
</body>
</html>

Output:

Element is present in the list at the position : 2
Element is not present in the list

Next Topic#




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf