[Solved] Why am I stuck in displaying my linked list?


You weren’t assigning newnode to newnode->next, therefore no linked list was being created.

But your code in the linked list doesn’t break or anything, it prints the values you wanted, just not in a linked list. The problem may be with conio.h, which is of no use in this code. remove #include <conio.h> and getch_();

To do exactly what you want, the exact way you want, we can create a contructor for node, which “automatically” adds the data to the new node.

Then in the display, you have to say that newnode is equal to the next node of newnode, which is a new node of a certain data (newnode = newnode->next = new node(SOME_DATA)). Only this way a linked list is being created.

#include <iostream>

using namespace std;

struct node {
  int data;
  node *next;
  node(int data){
      this->data = data;
  }
};

class list {
  node *head;
public:
  void display();
};

void list::display() {

  node *newnode = head = new node(2);
  newnode = newnode->next = new node(2);
  newnode = newnode->next = new node(1);
  cout << newnode->data;
  newnode = newnode->next = new node(2);
  cout << " " << newnode->data;
  newnode = newnode->next = new node(1);
  newnode = newnode->next = new node(4);
  cout << endl;
  cout << newnode->data;
  newnode->next = NULL;
}

int main() {
  list ab;
  ab.display();
}

1

solved Why am I stuck in displaying my linked list?