I want an explanation for how I can get to the Nth node in the linked list as to insert a node after that Nth node I have this piece of code and the function for inserting a node after the nth node is given as
InsertAfter
I have problem as how to call the function InsertAfter
in the driver main function i.e. if i have to go to the node next to the head I may write as head -> next
but, is this necessary to write next -> next
for the elements to go beyond the second node .
Is there any simple way which help me not to write next
for every node to jump to the next node.
For examples --> If I have to insert node after 7, I have to write head-> next-> next
but is there any easy way in which there is no need to next
again and again.
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
};
Node* head = NULL;
void insert(int x)
{
Node* temp = new Node();
temp -> data = x;
temp -> next = head;
head = temp;
}
void display(){
Node* temp;
temp = head;
while(temp != NULL)
{
cout<< temp -> data<< " ";
temp = temp-> next;
}
}
void insertAtLast(int x)
{
Node* temp = new Node();
Node* last = head;
temp -> data = x;
temp -> next = NULL;
if(head == NULL)
{
head = temp;
return;
}
while (last -> next != NULL)
{
last = last-> next;
}
last -> next = temp;
return;
}
void InsertAfter(Node* prev, int data)
{
if(prev == NULL)
{
cout<< "The previous node cannot be NULL" << endl;
return;
}
Node* temp = new Node();
temp -> data = data;
temp -> next = prev -> next;
prev->next = temp;
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: \n";
display();
cout<< endl;
insertAtLast(6);
display();
std::cout << '\n';
InsertAfter(head->,3);
display();
return 0;
}