gpt4 book ai didi

c++ - 链表中的头节点

转载 作者:行者123 更新时间:2023-11-30 02:32:25 25 4
gpt4 key购买 nike

下面的天真代码实现了一个链表,不打印主函数中的所有元素,一切都会好起来的。但是,LinkedList::printll 函数会触发一个设置错误(Gcc 5.3.0),我想这个问题与头节点的适当处理有关......

那么,有什么方法可以使这段代码在对 printll 函数进行最少修改的情况下工作吗?

#include <iostream>

using namespace std;

struct Node{
int value;
Node* next;
};

struct LinkedList{
Node* head= NULL ;
void append(int);
void printll();
};

void LinkedList::append(int data){
Node* cur = head;
Node* tmp = new Node;
tmp->value = data;
tmp->next = NULL;

if(!cur){
cur = tmp; // cur-> head
}
else{
while(cur->next != NULL){
cur = cur->next;
}
cur->next = tmp;
}
std::cout<<cur->value<<std::endl; // cur-> temp
delete tmp; // comment out
}

void LinkedList::printll(){
Node* cur = head;
while(cur->next != NULL){ //
std::cout<<cur->value<<std::endl;
cur = cur->next;
}
}


int main(){
LinkedList LL;
LL.append(5);
LL.append(6);
LL.append(7);
LL.printll(); // --without this, the program is fine
return 0;
}

最佳答案

你在 append 中有一些错误:

if(!cur){
cur = tmp;
}

这只分配给本地拷贝。我假设您正在尝试在此处设置 head,那么请这样做:head = tmp;。请注意,在这种情况下,您无法打印 cur,因为您尚未设置它。不过,您可以打印 tmp->value

然后:

delete tmp;

您刚刚创建它并将其分配到位 - 为什么要删除它?您知道仍然有指向它的指针。只有当你用完它来清理列表时才删除它(你现在根本不这样做)。

除此之外,您的 printll 不会打印最后一个元素 - 想想它什么时候会停止:

A -> B -> C -> NULL

它将在节点 C 上停止,但永远不会打印 C 的值。你可以只替换:

while(cur->next != NULL){

while(cur != nullptr){

(另外,我不喜欢 endl )。

See here for these changes running :

#include <iostream>

struct Node{
int value;
Node* next;
};

struct LinkedList{
Node* head = nullptr ;
void append(int);
void printll();
};

void LinkedList::append(int data){
Node* cur = head;
Node* tmp = new Node;
tmp->value = data;
tmp->next = nullptr;

if(!cur){
head = tmp;
}
else{
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = tmp;
}
}

void LinkedList::printll(){
Node* cur = head;
while(cur != nullptr){
std::cout << cur->value << '\n';
cur = cur->next;
}
}


int main(){
LinkedList LL;
LL.append(5);
LL.append(6);
LL.append(7);
LL.printll();
}

关于c++ - 链表中的头节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36470838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com