LinkedList in C++ | Sololearn: Learn to code for FREE!


LinkedList in C++

#include <iostream> #include <string> struct listNode { int numOfBirds; listNode * next; }; void totalBirds(){ if(temp ->next == NULL){ ; } } int main() { listNode * node = new listNode; listNode * temp = node; node -> numOfBirds = 7; node = new listNode; node -> numOfBirds = 5; temp -> next = node; temp = temp -> next; node = new listNode; node -> numOfBirds = 3; temp -> next = node; temp = temp -> next; node = new listNode; node -> numOfBirds = 10; temp -> next = node; temp = temp -> next; node = new listNode; node -> numOfBirds = 2; temp -> next = node; temp = temp -> next; node -> next = NULL; totalBirds(); return 0; };

12/31/2019 9:34:16 PM

Leo Hunter

3 Answers

New Answer


It would help if you ask a question. I see problems in the code but it would help if you made your problems clear with a question. This code has some problems like: - totalBirds being nearly empty. It needs a parameter to know what list to work with. To do what the name suggests, calculate total birds, it needs to iterate through all nodes in a list. - No reference to the last created node with 2 in it is kept. This makes the node useless and leads to memory leaks. - The program has memory leaks. They're pretty minor since the program closes soon and the memory would be implicitly freed when the program closes but you should learn something. Every time "new" is used, "delete" should also be used. - There is a lot of code duplication in main that adds nodes to the list. It could be improved with a new function. Here is updated code that fixes the issues mentioned above: #include <iostream> #include <string> struct listNode { int numOfBirds; listNode * next; }; int totalBirds(struct listNode * firstNode) { int result = 0; while ( firstNode != NULL) { result += firstNode->numOfBirds; firstNode = firstNode->next; } return result; } struct listNode * addToBeginningOfList(int numOfBirds, struct listNode *firstNode) { struct listNode * result = new listNode; result->numOfBirds = numOfBirds; result->next = firstNode; return result; } void freeList(struct listNode * firstNode) { // if the list is empty. if (firstNode == NULL) { return; } struct listNode * next = firstNode->next; delete firstNode; freeList(next); // free the rest of the list recursively. }; int main() { listNode * temp = addToBeginningOfList(7, NULL); temp = addToBeginningOfList(5, temp); temp = addToBeginningOfList(3, temp); temp = addToBeginningOfList(10, temp); temp = addToBeginningOfList(2, temp); std::cout << "Expected 27 and found " << totalBirds(temp); freeList(temp);


Hi Josh, thank you for your answer. I did have a question but for some reason only the code was sent. What I was doing is counting the number of birds in each node recursively, but I kept getting 'temp is not declared in the scope' as an error, that is why I didn't finish it. I'm very new to C++ lol. But I can learn from what you have sent me. Thanks again