[英]Program crashes while adding a new node in linked list in c++
I am trying to implement an insert function of the linked but as soon as I add the third element the program just crashes and execution is stopped, even though the same code worked on hackerrank's compiler.我正在尝试实现链接的插入功能,但是一旦我添加了第三个元素,程序就会崩溃并停止执行,即使相同的代码在hackerrank的编译器上工作也是如此。
Here is my code.这是我的代码。
#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;
}
The line线
while(head -> next != nullptr) current = current -> next;
in the function insert_tail
is wrong.在函数
insert_tail
是错误的。 It will run endlessly when head->next
is not nullptr
.当
head->next
不是nullptr
时,它将无休止地运行。
It should be它应该是
while(current -> next != nullptr) current = current -> next;
Here is a typo这是一个错字
while(head -> next != nullptr) current = current -> next;
^^^^^^^^^^^^
Write写
while(current -> next != nullptr) current = current -> next;
^^^^^^^^^^^^
An alternative definition of the function can look the following way,该函数的另一种定义可以如下所示,
void insert_tail( Node * &head, int data )
{
Node **current = &head;
while ( *current ) current = &( *current )->next;
*current = new Node( data );
}
And the function can be called simply like该函数可以简单地调用
insert_tail(head, 1);
Also the function print_linkedlist
can be written like函数
print_linkedlist
也可以写成
std::ostream & print_linkedlist( const Node * head, std::ostream &os = std::cout )
{
for ( ; head; head = head->next )
{
os << head -> data << " -> ";
}
return os << "nullptr";
}
and can be called like并且可以被称为
print_linkedlist(head) << '\n';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.