In the below code there is a node pointer naya
in the mn function. In the if
condition first time the naya
pointer is pointing to the null and we are trying to access its data. If we try to do the same code without the brackets around the naya
pointer, then it gives error such as:
prog.cpp: In function ‘void mn(Node*, Node**)’:
prog.cpp:66:50: error: request for member ‘data’ in ‘* naya’, which is of pointer type ‘Node*’ (maybe you meant to use ‘->’ ?)
if(*naya == NULL || temp -> data <= *naya -> data)
^*
But when we are using the brackets its' working fine. Why?
Below is the whole code:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next = NULL;
Node(int x) {
data = x;
next = NULL;
}
};
void mn(Node* temp, Node** naya) {
Node* current;
if (*naya == NULL || temp->data <= (*naya)->data) {
temp->next = *naya;
*naya = temp;
} else {
current = *naya;
while (current->next != NULL && (current->next->data < temp->data)) {
current = current->next;
}
temp->next = current->next;
current->next = temp;
}
}
Node* isort(Node* head) {
Node* temp = head;
Node* naya = NULL;
while (temp != NULL) {
Node* nex1 = temp->next;
mn(temp, &naya);
temp = nex1;
}
return naya;
}
void printll(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data;
temp = temp->next;
}
}
int main() {
Node *head = NULL, *temp = NULL;
int a;
cin >> a;
for (int i = 0; i < a; i++) {
int x;
cin >> x;
Node* newnode = new Node(x);
if (head == NULL) {
head = newnode;
temp = head;
} else {
temp->next = newnode;
temp = temp->next;
}
}
head = isort(head);
printll(head);
}