Question: Hello, the current code is listed below. I am able to create and print the list but i am unable to insert a node in

Hello, the current code is listed below. I am able to create and print the list but i am unable to insert a node in any posisiton of the lnked list that i create. Any help with this is greatly appreciated!

Consider the following struct Node. Write a function insertIth(headPtr, pos, value) which takes a pointer to a linked list pointed to by headPtr and adds a new Node with value as its data in the posth position of the resultant list.

If pos is 0, then the new Node will be first. If pos is greater than the length of the current list, the new Node will be last.

struct Node

int data;

Node * next;

Example Usage

// If list[1->[3->[5-> nullptr;

insertIth(list,0,7); // results in list[7->[1->[3->[5->nullptr;

// If list[1->[3->[5-> nullptr;

insertIth(list,2,7); // results in list[1->[3->[7->[5-> nullptr;

Here is my current code:

#include using namespace std;

struct Node { int data; Node * next; };

void insertIth(Node * &headPtr, int pos, int value); void createList(Node * headPtr, int lengthOfList); void printList(Node * headPtr, int lengthOfList);

int main() { Node * headPtr = new Node();

int length = 0; cout << "How long would you like the list to be (ex: 3 will make it 3 long): " << endl; cin >> length; createList(headPtr,length); printList(headPtr, length); insertIth(headPtr, 0, 7); cout << endl; printList(headPtr, length); return 0; }

void insertIth(Node * &headPtr, int pos, int value) { Node * tempPtr = headPtr; Node * tempPtr2; int count;

if (pos == 0) { headPtr = new Node(); headPtr->data = value; headPtr->next = tempPtr; }

else { while ((tempPtr != nullptr) && (count < pos - 1)) { tempPtr = tempPtr->next; count++; } } tempPtr2 = tempPtr->next; tempPtr->next = new Node(); tempPtr->next->data = value; tempPtr->next->next = tempPtr2;

}

void createList(Node * headPtr, int lengthOfList) { Node * tmp = headPtr; int userInput = 0;

for (int i = 0; i < lengthOfList - 1; i++) { cout << "Data to be inserted in the node: "; cin >> userInput;

tmp->data = userInput; tmp->next = new Node(); tmp = tmp->next; } cout << "Data to be inserted in the node: "; cin >> userInput;

tmp->data = userInput; tmp->next = nullptr; }

void printList(Node * headPtr, int lengthOfList) { Node * tmp = headPtr;

for (int i = 0; i < lengthOfList - 1; i++) { cout << tmp->data << "->"; tmp = tmp->next; } cout << tmp->data; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!