我正在 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 found\n";
else std::cout << "value not found\n";
}
當我在searchVal()函式內呼叫main函式時,它會輸出value not found,而值 4 在鏈表內。我的代碼有什么問題?
uj5u.com熱心網友回復:
當我在 main 函式中呼叫 searchVal() 函式時,它會輸出未找到的值,而值 4 在鏈表中。我的代碼有什么問題?
就在你打電話之前,searchVal(4)你 call traverseLinkedList(),并traverseLinkedList()以這樣的方式實作,當它回傳時,this->headwill be NULL,這意味著此時你的鏈表是空的(并且你已經泄漏了記憶體)。您需要修改traverseLinkedList()并且searchVal()不更改this->head(或物件的任何其他成員變數LinkedList)的值,以便它們不會修改串列的狀態作為副作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437074.html
上一篇:帶有類初始化的回圈非常慢
