Interesting problem with a Single Linked List #CPP | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Interesting problem with a Single Linked List #CPP

Hi everyone. I was doing a SLL code that adds an element to the list and i also tried to implement a function that traverses it. The problem is that i get a segmentation fault because the add function is not capable of adding the element. In the add function i use a temporary variable to match it with the head of the list, everything is "ok" at that moment but then when i traverse the list to get to the last node, i assign the temp variable (wich is a pointer to the head) to a new node but it never changes. I've tried making the temporary variable to a double pointer but that just denies me the use of the "->" operator and also the dot. Does anybody has a clue on what is happening here? I would appreciate a lot if anyone could help me. Here's the link to the code: https://code.sololearn.com/cL7hDZI2pI57

15th Apr 2022, 8:58 PM
Oscar Ramírez Díaz
Oscar Ramírez Díaz - avatar
2 Answers
+ 1
Hello Oscar Ramirez Diaz, An SLL is supposedly, and commonly implemented as a collection of Node class, represented as pointers, chained one to another. Your code doesn't have any definition of Node class, please review the concept again : )
15th Apr 2022, 9:18 PM
Ipang
+ 1
Line 28, your assertion "Temp is matched to the head" is false. It is matched to the second element. You need: LinkedList *temp = this; Also, you need to tie in the new node into the existing list. temp = new LinkedList(x); ain't gonna do it. But I agree with Ipang that you should revise your design choices again. For example, to traverse your list x, you need to call: x->traverse(x); which feels unnatural and unintuitive, since traverse knows it is called on x (it is its own method!), there is no need to pass x a second time.
16th Apr 2022, 5:56 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar