I made a method print
to print all elements of a linked list. I saw the implementation on YouTube, and I wrote the same code. it made an infinite loop while the code in the video on YouTube goes fine.
Why did that happen? One of my colleges told me to search about "ptrnull", and I searched but can't understand, and I used "brad" but it didn't give the reason.
#include <iostream>
using namespace std;
#define nl endl
struct MyNode {
int val; // value
MyNode *next; // address
};
class MyLinkedList {
private :
MyNode *head = NULL;
int size = 0;
public:
void insertFirst(int val)
{
MyNode *node = new MyNode;
node->val = val;
// if the linked list is empty
if (head == NULL)
{
head = node;
}
else
{
// the linked list is not empty
node->next = head;
head = node;
}
size++;
}
// to print all elements
void print()
{
MyNode *temp = head;
while (temp != NULL)
{
cout << temp->val << nl;
temp = temp->next;
}
}
int getSize()
{
return size;
}
};
int main() {
MyLinkedList list1;
list1.insertFirst(1);
list1.insertFirst(2);
list1.insertFirst(3);
list1.insertFirst(4);
cout << list1.getSize() << nl;
list1.print();
return 0;
}