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?
-
$\begingroup$ What did you try? Where did you get stuck? We're happy to help you understand the concepts but just solving exercises for you is unlikely to achieve that. You might find this page helpful in improving your question. $\endgroup$– NathanielJan 12 at 12:39
-
$\begingroup$ This homework is elementary. What is the problem ? $\endgroup$– user16034Jan 12 at 14:00
1 Answer
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.
Iterative Approach:
- 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$