I am implementing a linked list but it doesn't display any output.
implementing a linked list with 4 elements and making fuction insert and insertathead and display.
#include <bits/stdc .h>
using namespace std;
// class node to make node element.
class node
{
public:
int data;
node *next;
node{
}
// constructor
node(int val)
{
data = val;
next = NULL;
}
// function to insert element at head.
void insertAthead(node *&head, int val)
{
node *n = new node(val);
n->next = head;
head = n;
return;
}
// function to insert in linked list.
void insert(node *head, int val)
{
node *temp = head;
if (head == NULL)
{
insertAthead(head, val);
return;
}
node *n = new node(val);
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
// function to display each element in a linked list.
void display(node *head)
{
while (head->next != NULL)
{
cout << head->data;
head = head->next;
}
cout << head->data;
}
};
//main function
int main()
{
node *head; // line at which I think there is a problem
head->insert(head, 1);
head->insert(head, 2);
head->insert(head, 3);
head->insert(head, 4);
head->display(head);
return 0;
}
I think the problem is at line 1
node *head;
when I change this line with node *head=new node(any integer value) the code runs fine.
CodePudding user response:
First you want to move insert, insertAtHead and display out of the Node class. These are list functions have have no need of special access to Node.
Also you should initialise head to NULL (representing the empty list).
This means changing main like this
node *head = NULL;
insert(head, 1);
insert(head, 2);
insert(head, 3);
insert(head, 4);
display(head);
Then you want to change
void insert(node *head, int val)
to
void insert(node *&head, int val)
Just like you have done (correctly) with insertAtHead.
If you wanted to take this further you could create a List class, along these lines
class List
{
public:
List() { root = NULL; }
void insert(int val);
void insertAtHead(int val);
void display();
private:
Node* root;
};
then main would look like this
int main()
{
List l;
l.insert(1);
l.insert(2);
l.insert(3);
l.insert(4);
l.display();
}
