'Linked list search function not working properly

I am making a LinkedList class in C++ with its methods, like adding nodes, traversing, and searching. When implementing the search function, it seems not working properly because it does not find the value in linked list when in fact it is inside the linked list. The code is shown below.

#include <iostream>

class Node {
    public:
        int value;
        Node* next;
        
        Node(int value, Node* next) {
            this->value = value;
            this->next = next;
        }
};

class LinkedList {
public:
    Node* head;
    Node* tail;
    
    LinkedList() {
        this->head = nullptr;
        this->tail = nullptr;
    }
    
    LinkedList(Node* node) {
        this->head = node;
        this->tail = node;
    }
    
    void addNodeFront(Node* node) {
        if(head==nullptr && tail==nullptr) {
            this->head = node;
            this->tail = node;
            return;
        }
        this->tail = this->head;
        this->head = node;
        node->next = tail;
    }
    
    void addNodeBack(Node* node) {
        if(head==nullptr && tail==nullptr) {
            this->head = node;
            this->tail = node;
            return;
        }
        this->tail->next = node;
        this->tail = node;
    }
    
    void addNodeAfterNode(Node* prevNode, Node* node) {
        node->next = prevNode->next;
        prevNode->next = node;
    }
    
    bool searchVal(int val) {
        while(this->head != nullptr) {
            if(this->head->value == val) return true;
            this->head = this->head->next;
        }
        return false;
    }
    
    void deleteNode(Node* node) {
        Node* prevNode = this->head;
        while(prevNode->next != node) {
            
        }
    }
    
    void traverseLinkedList() {
        while(this->head!=nullptr) {
            std::cout << this->head->value << "->";
            this->head = this->head->next;
        }
        std::cout << "\n";
    }

    void sortLinkedList() {
        
    }
};

int main() {
    Node node1(2,nullptr);
    Node node2(4,nullptr);
    Node node3(3,nullptr);
    LinkedList ls;
    ls.addNodeFront(&node1);
    ls.addNodeBack(&node3);
    ls.addNodeAfterNode(&node3, &node2);
    ls.traverseLinkedList();
    if(ls.searchVal(4)) std::cout << "value found\n";
    else std::cout << "value not found\n";
}

When I call the searchVal() function inside the main function it outputs value not found while value 4 is inside the linked list. What is wrong with my code?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source