Search Element

Search a element in the linked list.

  1. Just check did list contains the element or not, if contains return true else return false.
  2. Search element and if found then return the position of it.
  3. Search element if found then return node object of it.

Implementation of above requirements.

-> Search a element if found return true else return false

a. Create a method which receives a  search element as argument and returns boolean.

b. First check is list empty.

c. If list it not empty then create a copy of head and loop the it till data find.

private static boolean isContain(String data) {
    if(head == null ){
        return false;
    }
    Node temp = head;
    while (temp != null){
        if (temp.data.equals(data) )
        return true;

        temp = temp.next;
    }
    return false;
}

-> Search element if found then return position.

a. Create a method which takes search element as argument and returns integer as a position.

b. Check is list empty, if empty then return -1.

c. Check head is given element if yes then return 0. If not then create a copy of head node.

d. Create a counter and set it to 0. traverse the list and increment the counter. Add a condition to check the element. if found then return the counter.

private static int searchElement(String data) {
    if(head == null ){
        return -1;
    }
    if(head.data.equals(data))
        return 0;
    Node temp = head;
    int counter = 0;
    while (temp != null ){
        if(temp.data.equals(data))
            return counter;
        counter++;
        temp = temp.next;
    }
    return -1;
}

-> Search a element if found then return the Node object of it.

a. Create a method which receive the search element as argument and return type is Node.

b. Check list is empty. if empty then return null.

c. Check is head same as given element then return head.

d. if above 2 are not satisfied then create a copy of head. now traverse the list till find if found then return the node.

private static Node searchNode(String data) {
    if(head == null ) {
        return null;
    }
    Node temp = head;
    while (temp != null ){
        if(temp.data.equals(data))
        return temp;
        temp = temp.next;
    }
    return null;
}