我正在尝试将元素添加到列表中,但是失败。
当我尝试输出列表时,列表似乎始终没有改变。
样本输入:1 3
样本输出:1 3
有人可以告诉我为什么以及如何解决吗?
这是节点和列表
struct Node {
int value;
Node* next;
Node(const int& val = 0, Node* nextnode = nullptr)
: value(val), next(nextnode) {}
};
class List {
public:
List() : head(new Node) {}
void CreateList(int n);
void insert_to_end(int val);
void transe_list() const {
for (Node* i = head->next; i != nullptr; i = i->next) {
cout << i->value << " ";
}
}
private:
Node* head;
};
void List::CreateList(int n) {
int value;
Node* temp = head;
while (--n >= 0) {
cin >> value;
Node* nextnode = new Node(value);
temp->next = nextnode;
temp = nextnode;
}
}
void List::insert_to_end(int val) {
Node* temp = head->next;
while (temp != NULL) {
temp = temp->next;
}
temp = new Node(val);
}
这是main()
int main(int argc, char const* argv[])
{
List intList;
intList.CreateList(2);
intList.insert_to_end(9);
intList.transe_list();
system("pause");
return 0;
}
答案 0 :(得分:0)
在List::insert_to_end
中,您只更改了局部变量temp
,这对列表的状态没有影响(并且会泄漏内存)。这应该起作用:
void List::insert_to_end(int val) {
Node* temp = head; // start with head
while (temp->next != NULL) { // iterate until end, then temp points to the last node
temp = temp->next;
}
temp->next = new Node(val); // append new node as follower to the currently last node
}
请记住,当列表尚未初始化且head
为nullptr
时,您需要处理特殊情况,但具体实现取决于您。