Reflection on My Implementation of Singly Linked List
My Implementation and Problems
My implementation with int type link list
When I tried to implement a linked list started from int type, I face little problems.
I used a incorrect deletion logic when I try to clear all the nodes in singly linked list: I try to delete from end and face double memory free error when running the program.
1 | void clearAllNode(){ |
- I attempted to delete the last node by traversing to the end of the list, and then somehow referencing the “second-last” node afterward.
- I incorrectly assigned
currentNodetolastNodeafter traversingcurrentNodeto the end of the list usingcurrentNode = currentNode->nextNode;. My intention was to makelastNoderepresent the node before the last one. However, in this case, bothcurrentNodeandlastNodeended up referring to the same node, because I assignedlastNodeaftercurrentNodehad already moved to the last node. - But since a singly linked list only points forward, once I delete the last node, I lose access to the previous one. This caused a bug or crash
- especially when I tried to access a freed node
How to Fix
If I insist on deleting nodes from the end of a singly linked list, I must:
- Traverse the list each time to find the second-last node
- Delete the last node.
- Set the second-last node’s
nextNodetonullptr - Do that again and again until
headpoints tonullptr
1 | void clearAllNode(){ |
Better Practice and Why
I can’t efficiently delete from the end in a singly linked list because:
- Each node only has a pointer to the next node, not the previous one.
- To delete the last node, I must traverse the entire list from the beginning to find:
- The last node, to delete it.
- The second-last node, so I can set its
nextNode = nullptr.
That means:
- I cannot just move backward in the list.
- Deleting every node from the end means traversing the list N times, making the time complexity O(n²) for clearing. How to Calculate O(n) Complexity
Better practice for me to clear all nodes from a singly linked list is delete from head
1 | void clearAllNode(){ |
- Title: Reflection on My Implementation of Singly Linked List
- Author: Ricardo Pu
- Created at : 2025-04-21 22:01:47
- Updated at : 2025-04-21 22:40:19
- Link: https://ricardopotter.github.io/RicardoBlog/2025/04/21/Reflection-on-My-Implementation-of-Singly-Linked-List/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments