Home > Mobile >  logical error in singly linked list code c
logical error in singly linked list code c

Time:12-04

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

CodePudding user response:

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;

CodePudding user response:

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;
  • Related