0

Inserting elements in linked list in c++ not working

/* i was learning data structures from youtube and followed the youtuber's code the code worked for her but when i run the program the terminal becomes blank (no output) I dont know whats wrong with my code it compiles perfectly without any errors */ #include <iostream> using namespace std; class node { public: int value; node *next; }; // passing linked list to function as well as printing values stored in linked list void printList(node *n) { while (n != NULL) { cout << n->value << endl; n = n->next; // changing n to n.next[head->value to head->next] } } // Inserting elements at the front of the linked list using function void insertAtTheFront(node **head, int newValue) // passing adress to the pointer when calling the fuction so passing pointer to the pointer i.e node **head { // this function needs to perform 3 things to add new node to front // 1. Prepare a new node node *newnode = new node(); newnode->value = newValue; // 2.Put it infront of current head(first element) newnode->next = *head; // 3.Move head of the list to point to newNode *head = newnode; } // Inserting elements at the back of the linked list void insertAtTheEnd(node **head, int newValue) { // Four steps // 1.Prepare a new node node *newnode = new node(); newnode->value = newValue; newnode->next = NULL; // 2. If linnked list is empty newnode will be head if (*head == NULL) { *head = newnode; return; } // 3.Find the last node node *last = *head; // introducing new node while (last->next != NULL) { *head = newnode; } // 4. insert newnode after last node(at the end) last->next = newnode; } //i have omitted the main function

27th Jul 2022, 12:36 PM
Samir_Shah
Samir_Shah - avatar
1 Resposta
+ 1
You might improve your chances for answers if you share your code bit link rather than raw text snippet like this. It's easier to test code bit than raw text snippet,. Testing a code bit copy/paste hassle free, line number referencing is supported, syntax highlighting etc. https://www.sololearn.com/post/75089/?ref=app
27th Jul 2022, 1:20 PM
Ipang