我正在尝试实现链接的插入功能,但是一旦添加第三个元素,程序就会崩溃并停止执行,即使相同的代码在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;
}