[英]The head node in a linked list
下面的天真代码实现了一个链表,而不打印main函数中的所有元素,一切都会好的。 但是, 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;
您只是创建它并将其分配到位 - 为什么要删除它? 你知道还有一个指向它的指针。 只有delete
当你来到清理名单,当你用它做(你不要在此刻做的话)它。
除此之外,你的printll
不会打印最后一个元素 - 想想它什么时候会停止:
A -> B -> C -> NULL
它将在节点C
上停止,但从不打印C
的值。 你可以替换:
while(cur->next != NULL){
同
while(cur != nullptr){
(另外,我不喜欢endl
)。
#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();
}
你不能
delete tmp;
导致tmp是一个指针,当你运行delete tmp时,你删除了该对象。
2.打印功能应该是这样的:
void LinkedList::printll(){
Node* cur = head;
while(cur->next != NULL){ // -> problems is here
std::cout<<cur->value<<std::endl;
cur = cur->next;
}
std::cout<<cur->value<<std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.