我正试图实现链接的插入函数,但一旦添加第三个元素,程序就会崩溃并停止执行,即使在hackerlink的编译器上也使用了相同的代码。
这是我的密码。
#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;
}
行
while(head -> next != nullptr) current = current -> next;
函数CCD_ 1中的错误。当head->next
不是nullptr
时,它将无休止地运行。
应该是
while(current -> next != nullptr) current = current -> next;
这是一个打字错误
while(head -> next != nullptr) current = current -> next;
^^^^^^^^^^^^
写入
while(current -> next != nullptr) current = current -> next;
^^^^^^^^^^^^
该函数的另一个定义可以如下所示,
void insert_tail( Node * &head, int data )
{
Node **current = &head;
while ( *current ) current = &( *current )->next;
*current = new Node( data );
}
该函数可以像一样简单地调用
insert_tail(head, 1);
此外,函数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";
}
可以称为
print_linkedlist(head) << 'n';