Answer to Question #273342 in C++ for Korea

Question #273342

Insert node specific position

1
Expert's answer
2021-11-30T00:36:45-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS