@Parmeet-Kalsi-1631789033630118,
Okay, see this code snippet,
class Node {
public:
int data;
Node* nxt;
Node(int x = 0) {
data = x;
nxt = NULL;
}
};
void push_front(Node* &head, int x) {
Node* temp = new Node(x);
temp->nxt = head;
head = temp;
}
void increment(Node* head) {
while (head) {
head->data++;
head = head->nxt;
}
}
void print(Node* head) {
while (head) {
cout << head->data << ", ";
head = head->nxt;
}
}
In this the push_front requires Node* &head because we permanently update the value of the head pointer declared in main, but the print function does not require a reference, because we do not update any pointer. Also, in increment we do some permanent changes on our linked list, but still we don’t need to pass a reference pointer, because we only make changes to the linked list, not the head pointer we have passed.
The head pointer remains same before and after the increment and print function calls, thus we don’t need to pass it by reference.
The head pointer itself changes (the list has a new head) after calling push_front, therefore we need to pass by reference.
Similarly, the replaceSum function in bhaiya’s implementation, does not change the actual head of the linked list, thus does not requires passing by reference.
Also, I am sure bhaiya emphasised on that point wrt his implementation, because otherwise generalising the statement that implementing linked list would indeed mean passing pointers by reference wouldn’t be very accurate as I can make a class like this and refrain myself from passing any sort of pointers.
class List {
class Node {
public:
int data;
Node* nxt;
Node(int x = 0) {
data = x;
nxt = NULL;
}
};
Node* head;
public:
List() {
head = NULL;
}
void push_front(int x) {
Node* temp = new Node(x);
temp->nxt = head;
head = temp;
}
void increment() {
Node* temp = head;
while (temp) {
temp->data++;
temp = temp->nxt;
}
}
void print() {
Node* temp = head;
while (temp) {
cout << temp->data << ", ";
temp = temp->nxt;
}
}
};