Reputation: 3
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* insert(Node *head,int data)
{
if(head == NULL){
head = new Node(data);
return head;
}
else if(head->next == NULL){
Node *temp = new Node(data);
head->next = temp;
return head;
}
else{
insert(head->next, data);
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
}
While defining the Node for a linked list why do we put a pointer in front of the class
i.e what does the statement Node* insert(Node *head,int data)
do and what would happen if instead if I define it as Node insert(Node *head,int data)
?
Upvotes: 0
Views: 341
Reputation: 2678
It is important to return the pointer to the start of the list. An empty list is one where head
points to NULL
(C) or nullptr
(C++), which both mean zero. When the memory of the first element is allocated and the Node is added, the address of that element is returned so that the main function can track the list's memory location.
If the list is emptied one element at a time, eventually the last call to the (hypothetical) delete
function will return 0 to signal that the list is empty again.
If we were to return the element directly using Node insert(Node n, int data)
the function would return a copy of the node instead of the actual node. That could maybe work provided that the function is modified as well, as the Node still has pointers inside it, but usually pointers are used.
If you were to just change the definition of the function to Node insert(Node *n, int data)
the code in all likelyhood wouldn't compile, as the head is of type Node *.
Upvotes: 1