I have made a linked list, I tried to find the reason why pointer is used in creating a linked list, but later I got stuck in it.
My doubt is Why the Val and Next pointer gets changed but the Node pointer itself isn’t changed.
Also, what’s the whole point of using pointers?
I know that passing with reference will change everything, but I am not clear with the above mentioned thing.
Here is the code:
#include<bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void change(ListNode* a) {
a->val = 500;
a->next = NULL;
a = NULL;
}
int main() {
ListNode* head = new ListNode(5);
head->next = head;
change(head);
cout << head->val << endl;
if (head == NULL)cout << "YESSS" << endl;
if (head->next == NULL)cout << "YES" << endl;
return 0;
}
Output:
500
YES