1

For the following code, the result that I'm aiming for is 4-->5-->, however the result that is outputted is only 4-->

For context, I'm trying to implement a singly linked list using structure and functions only in c++.

Code:

#include <iostream>
using namespace std;
struct node
{
    int data;
    node* next;
};
node* head = NULL;
void insert(int val)
{

    node* n = new node();
    n->data = val;


    if(head == NULL)
    {
        head = n;
    }
    else
    {
        node* temp = head;
        while(temp!=NULL)
        {
            temp = temp->next;
        }
        temp = n;
    }
}
void display()
{
    if(head == NULL)
    {
        cout<<"UNDERFLOW ! LINKED LIST IS EMPTY !"<<endl;
    }
    else
    {
        cout<<"LINKED LIST!"<<endl;
        node* temp = head;
        while(temp!=NULL)
        {
            cout<<temp->data<<"-->";
            temp = temp->next;
        }
        cout<<endl;
    }
}
int main()
{
    insert(4);
    insert(5);
    display();
    return 0;
}
2
  • 1
    Look real carefully at the append logic in insert. What's the value of temp when you assign n? Commented Dec 4, 2021 at 6:05
  • 😊👍, thank you, the comment was super helpful. Commented Dec 5, 2021 at 10:27

2 Answers 2

1

As rightly pointed by @StephenNewell, you have a bug in the insert function.

Also in C++, use nullptr instead of NULL.

Change the below code in insert():

node* temp = head;
while(temp!=NULL)
{
    temp = temp->next;
}
temp = n;

to:

node* temp = head;
while (temp->next != nullptr)
{
    temp = temp->next;
}
temp->next = n;
Sign up to request clarification or add additional context in comments.

2 Comments

it was really helpful, thankyou😊.
@jdsingh, if my answer was helpful, do consider up voting :-)
0

You question is temp is a temporary variable, and you just change the value of the temporary variable every time but not the last node of the linked list.

If you want to change the value of the pointer, you need the pointer of the pointer or You should change to

while(temp->next != NULL)
{
    temp = temp->next;
}
temp->next = n;

1 Comment

thank you so much for helping me out😊.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.