【问题标题】:Program crashes while adding a new node in linked list in c++在 C++ 中的链表中添加新节点时程序崩溃
【发布时间】: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 -&gt; next != nullptr) 这样的循环是有风险的,需要额外的测试来确保head 在第一个head -&gt; next 之前有效。我通常发现写while(head != nullptr) 并将初始测试构建到循环中会更好。

标签: c++ class data-structures linked-list singly-linked-list


【解决方案1】:

线

    while(head -> next != nullptr) current = current -> next;

在函数insert_tail 中是错误的。当head-&gt;next 不是nullptr 时,它将无限运行。

应该是

    while(current -> next != nullptr) current = current -> next;

【讨论】:

    【解决方案2】:

    这里有错别字

    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';
    

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 2019-05-23
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多