I\'ve missed the last 2 weeks of school and am lost in my programming class. I n
ID: 3641762 • Letter: I
Question
I've missed the last 2 weeks of school and am lost in my programming class.I need to write a function to insert a new entry into a linked list. Have
the procedure take as arguments a pointer to the list entry to be inserted of type
struct entry (defined below) and a pointer to an element in the list
after which the new entry is to be inserted.
struct entry
{
int value;
struct entry *next;
};
I doubt it, but if anyone could write this function it would be extremely appreciated.
Explanation / Answer
#include using namespace std; struct entry { int value; struct entry *next; }; typedef entry *ptr; //in this function we will iterate the list and insert a new value void iterateAndInsert(entry* ptr, int val) { while(ptr->next->value!=NULL) { ptr= ptr->next; } //we have arrived at the end of the list and we are about to insert our value ptr->next = new entry; ptr = ptr->next; ptr->value = val; ptr->next = new entry; } void insertIntoLinkedList(entry* ptr,int val) { //are we sure we are not overriding any data? if(ptr->next==NULL && ptr->value==NULL) { ptr->value = val; ptr->next = new entry; } } //I didint bother with the c version it is the same except for the cout and printf void printLinkedList(entry* head) { while(head->next!=NULL) { cout next = new entry; // now the head points to the front of the list //Now we have to make another ptr, to insert into the list entry *ptr = head->next; //and here we can use the function i think you asked for insertIntoLinkedList(ptr,2); //create a new spot in the list ptr->next = new entry; //and place our pointer there so it is ready to insert the element ptr = ptr->next; insertIntoLinkedList(ptr,3); ptr->next = new entry; ptr = ptr->next; insertIntoLinkedList(ptr,4); //another method tested for better understanding iterateAndInsert(head,5); //just for geek kicks lets insert our head and make it iterate and insert;) iterateAndInsert(head,6); iterateAndInsert(head,7); //now for the finale part iterateAndInsert(ptr,8); //print the list, takes in the head of the list and prints it out printLinkedList(head); return 0; } Hi, I did this for you in C++ the only difference is the cout and the printf() which you can fix with out to much trouble. The code is commented and I hope you read it and follow along with it. Good luck in your studies!Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.