【发布时间】:2021-02-11 05:48:15
【问题描述】:
我正在尝试实现链接的插入功能,但只要我添加第三个元素,程序就会崩溃并停止执行,即使相同的代码在hackerrank的编译器上工作。
这是我的代码。
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node * next;
Node(int data){
this -> data = data;
this -> next = nullptr;
}
};
Node * insert_tail(Node * head, int data){
Node * node = new Node(data);
if(head == nullptr) return node;
Node * current = head;
while(head -> next != nullptr) current = current -> next;
current -> next = node;
return head;
}
void print_linkedlist(Node * head){
while(head -> next != nullptr){
cout << head -> data << " -> ";
head = head -> next;
}
cout << head -> data << " -> nullptr";
}
int main(){
Node * head = nullptr;
head = insert_tail(head, 1);
head = insert_tail(head, 5);
head = insert_tail(head, 3);
head = insert_tail(head, 5);
head = insert_tail(head, 8);
head = insert_tail(head, 17);
print_linkedlist(head);
return 0;
}
【问题讨论】:
-
执行崩溃在哪一行?
-
您应该学习使用调试器并逐步执行代码以查看发生了什么。
-
很抱歉我添加了定义,但正如@MikeCAT 所说,这是一个逻辑错误。
-
我是 C++ 新手,你能给我一些关于如何使用调试器的教程吗?
-
战术说明:像
while(head -> next != nullptr)这样的循环是有风险的,需要额外的测试来确保head在第一个head -> next之前有效。我通常发现写while(head != nullptr)并将初始测试构建到循环中会更好。
标签: c++ class data-structures linked-list singly-linked-list