Given any singly linked-list L storing n real keys, that is, each key in L belongs to R, design an algorithm (either in words or in pseudocode) that computes the sum of the negative keys in L. What is the running time of your algorithm, in the worst-case, using O notation?
This is a basic question on linked lists.
You have to understand that for these types of problems, there are 2 different solutions. The iterative approach, or the recursive approach. Here, the iterative approach is easier.
- Define a new variable, $Sum = 0$.
- Iterate through the list.
- Check the data of the list. If it's negative, add it to sum. $Sum$ $-$$=$ $list\rightarrow data$.
- Else, iterate to the next node in the list.
- Exit once you reach the last node. (last node means that $list\rightarrow next=NULL$