Hi! I am new to data structures.
I am trying to make a linked list using a for loop. I was expecting output to be 1 2 3 4 5
instead I am getting 0
as output.
Can someone please explain my mistake?
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
void printLL(Node* n)
{
while (n != NULL)
{
cout << n->data << " ";
n = n->next;
}
}
int main()
{
int value;
Node *head, *newNode = NULL, *temp = NULL;
for (int i = 1; i <= 5; i++)
{
head = new Node();
newNode = new Node();
if (i == 1) //for the first node
{
head->data = i;
head->next = newNode;
}
else //for the rest of the nodes
{
newNode->data = i;
newNode->next = NULL;
}
}
printLL(head);
return 0;
}