Insert node specific position
#include <bits/stdc++.h>
using namespace std;
struct Node {
int d;
struct Node* nxt;
};
int n = 0;
Node* getNode(int d)
{
Node* new_n = new Node();
new_n->d = d;
new_n->nxt = NULL;
return new_n;
}
void insert(Node** curr, int p, int d)
{
if (p < 1 || p > n + 1)
cout << "Invalid position!" << endl;
else {
while (p--) {
if (p == 0) {
Node* temp = getNode(d);
temp->nxt = *curr;
*curr = temp;
}
else
curr = &(*curr)->nxt;
}
n++;
}
}
void display(struct Node* h)
{
while (h != NULL) {
cout << " " << h->d;
h = h->nxt;
}
cout << endl;
}
int main()
{
Node* h = NULL;
h = getNode(1);
h->nxt = getNode(2);
h->nxt->nxt = getNode(3);
h->nxt->nxt->nxt = getNode(4);
n = 4;
cout << "Before insertion: ";
display(h);
int d = 6, p = 3;
insert(&h, p, d);
cout << "After insertion of "<<d<<" at position "<<p;
display(h);
d = 7, p = 1;
insert(&h, p, d);
cout << "After insertion of "<<d<<" at position "<<p;
display(h);
d = 8, p = 2;
insert(&h, p, d);
cout << "After insertion of "<<d<<" at position "<<p;
display(h);
return 0;
}
Comments
Leave a comment