我正在尝试用 C++ 创建一个带有指针的链表结构。但似乎该节点未正确分配,并且我无法获得有关内部发生的情况的更多信息。
#include <iostream>
using namespace std;
struct LLNode{
int value;
LLNode* next = nullptr;
};
class LinkedList{
private:
int size;
LLNode* head;
LLNode* crr;
public:
// constructor
LinkedList(){
size = 0;
head = nullptr;
crr = nullptr;
}
/* create node with input value
* link the node to the end of the list
*/
int append(int value){
LLNode* node = new LLNode; node->value = value;
LLNode* current = head;
// add as head node
if(head == nullptr){
head = node;
}
// add at the end of nodes
else{
while(current->next != nullptr){
current = current->next;
}
current->next = node;
}
size++;
return current->next->value;
}
int main(){
LinkedList llist;
cout << llist.append(100) << endl;
return 0;
}
return current->next->value;
没有返回任何内容。可能是节点分配有问题?如果有的话怎么解决?
您的代码中存在一些错误:
#include <iostream>
using namespace std;
struct LLNode {
int value;
LLNode* next = nullptr;
};
class LinkedList {
private:
int size;
LLNode* head;
LLNode* crr;
public:
// Constructor
LinkedList() {
size = 0;
head = nullptr;
crr = nullptr;
}
//Create a node with the input value and link it to the end of the list
int append(int value){ // Added missing closing bracket here
LLNode* node = new LLNode;
node->value = value;
LLNode* current = head;
// Add as head node
if (head == nullptr) {
head = node;
} else { // Added missing else block here
// Add at the end of nodes
while (current->next != nullptr) {
current = current->next;
}
current->next = node;
}
size++;
return node->value; // Changed to return the value of the newly added node
}
}; // Added missing closing bracket for the class definition
int main() {
LinkedList llist;
cout << llist.append(100) << endl;
return 0;
}