简体   繁体   中英

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.

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. It will run endlessly when head->next is not 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM