ZIA ANSARI ZIA ANSARI - 1 month ago 11
C++ Question

Printing the singly linked list

I am a newbie to programming
Here I wrote a code for accepting and displaying the values using linked list.
However the code takes all the values but displays only the last value
Here is the code

#include <iostream>
using namespace std;
struct node {
int value;
node* next;
};
class llist {
public:
void create();
void display();
node* head = NULL;
};
void llist::create()
{
struct node* temp;
temp = NULL;
struct node* p;
p = new struct node;
cin >> p->value;

if (head == NULL) {
head = p;
}

else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->value = p->value;
temp->next = NULL;
}
}

void llist::display()
{
struct node* temp = head;
while (temp != NULL) {
cout << "VALUE:" << temp->value << endl;
temp = temp->next;
}
}

int main()
{
int n, i;
llist l1;
cin >> n;
for (i = 0; i < n; i++)
l1.create();
cout << "Displaying list\n";
l1.display();
return 0;
}


Input:

4

1

2

3

4

Displaying list

VALUE:4

I am wondering what went wrong...

Answer Source

Change this:

else {
    temp = head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->value = p->value;
    temp->next = NULL;
}

to this:

else {
    temp = head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = p;
}

When inserting a new element at the end of a linked list, you find the last element inside the while loop and put it in the temp variable. Then you assign its next value to your new p element. The way you were doing before, you were just overriding the integer number of the last element. That is why when you printed your list you only got the last number you entered.

Also, when creating a new element p, be sure to initialize its next value to NULL:

p = new struct node;
p->next = NULL;