链表搜索功能无法正常工作



我正在用C++制作一个LinkedList类,它的方法包括添加节点、遍历和搜索。当实现搜索功能时,它似乎工作不正常,因为它在链表中找不到值,而实际上它在链表内。代码如下所示。

#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 foundn";
else std::cout << "value not foundn";
}

当我在main函数内调用searchVal()函数时,它输出value not found,而值4在链表内。我的代码出了什么问题?

当我在主函数内部调用searchVal((函数时输出未找到的值,而值4在链表中。什么我的代码有问题吗?

就在调用searchVal(4)之前,您调用了traverseLinkedList(),而traverseLinkedList()的实现方式是,当它返回时,this->head将是NULL,这意味着此时您的链表是空的(并且您泄露了内存(。您将需要修改traverseLinkedList()searchVal()以不更改this->head(或LinkedList对象的任何其他成员变量(的值,这样它们就不会将修改列表的状态作为副作用。

最新更新