#include
using namespace std;
class node
{
public:
int data;
node *next; //self refrencial class
//constructor
node(int d)
{
data = d;
next = nullptr;
}
};
int length(node *head)
{
int len = 0;
while (head->next = NULL)
{
len++;
}
return len;
}
void insertatHead(node *&head, int data) //passing head by refrence and thus we can modify it
{
//if we have passed node*head it wouldnt pass the actual pointer but would pass its copy
//so only if copy is passed it will update the copy only and not the original value
//thus we wont get any output
node *n = new node(data); //node memory will remain forever but n is static pointer it will get destroyed
n->next = head;
head = n;
}
void insertatTail(node *&head, int data)
{
if (head == NULL)
{
insertatHead(head, data);
return;
}
node *tail = head;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = new node(data);
return;
}
void insertinMiddle(node *&head, int data, int p)
{
if (head == NULL || p == 0)
{
insertatHead(head, data);
}
else if (p > length(head))
{
insertatTail(head, data);
}
else
{
int jump = 1;
node *temp = head; //this will assign head to temp and we can use temp without altering head
while (jump <= p - 1)
{
temp = temp->next;
jump++;
}
node *n = new node(data);
n->next = temp->next;
temp->next = n;
}
}
void print(node *head)
{
while (head != NULL)
{
cout << head->data << " --> ";
head = head->next;
}
}
int main()
{
node *head = NULL;
insertatHead(head, 3);
insertatHead(head, 2);
insertatHead(head, 1);
insertatTail(head, 6);
insertinMiddle(head, 5, 3);
print(head);
return 0;
}
im not getting the desired output