微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C ++的链表中添加新节点时程序崩溃

如何解决在C ++的链表中添加新节点时程序崩溃

我试图实现链接的插入功能,但是一旦添加了第三个元素,程序就崩溃了,并且执行停止了,即使相同的代码在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,8);
    head = insert_tail(head,17);

    print_linkedlist(head);
    return 0;
}

解决方法

    while(head -> next != nullptr) current = current -> next;
函数insert_tail中的

错误。当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';

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。