#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
data;
Node* next;
};
Node* getNode(
int
data)
{
Node* newNode = (Node*)
malloc
(
sizeof
(Node));
newNode->data = data;
newNode->next = NULL;
return
newNode;
}
void
insertAfterNthNode(Node* head,
int
n,
int
x)
{
if
(head == NULL)
return
;
Node* newNode = getNode(x);
Node* slow_ptr = head;
Node* fast_ptr = head;
for
(
int
i = 1; i <= n - 1; i++)
fast_ptr = fast_ptr->next;
while
(fast_ptr->next != NULL) {
slow_ptr = slow_ptr->next;
fast_ptr = fast_ptr->next;
}
newNode->next = slow_ptr->next;
slow_ptr->next = newNode;
}
void
printList(Node* head)
{
while
(head != NULL) {
cout << head->data <<
" "
;
head = head->next;
}
}
int
main()
{
Node* head = getNode(1);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
int
n = 4, x = 2;
cout <<
"Original Linked List: "
;
printList(head);
insertAfterNthNode(head, n, x);
cout << "
Linked List After Insertion: ";
printList(head);
return
0;
}