Frage

As the title says, I need a way to add together the values in the nodes of the linked list.

When the user enters 7.4, 5.1, and 10.5 in the linked list, the answer '23' would be output when the user requests the total sum of values within the nodes.

I'm not asking for someone to write the code for me I am looking for a helpful tutorial that enables me to do it myself. I have already checked Google for tutorials but all I find is how to add nodes to linked lists. Not really what I want.

Any help would be greatly valued and appreciated.

War es hilfreich?

Lösung

Let me give you synopsis of code,

sum = 0;
while(node)
{
    sum += node->data;
    node = node->next;
}

hope you get the rest of idea by your self;

Andere Tipps

You need to :

  1. initialize a variable (sum) with 0.
  2. loop through the linked list
  3. add the value contained in the node to the sum variable as you visit each node.
  4. print the sum variable

This might be a wrong answer (depends on context) but why not keep track of the sum value of nodes ? So everytime a new element is added to the linked list the sum value is updated as well. The same applies when a node is removed (the removed value is subtracted from the sum).

This way you save yourself from iterating. This does not mean much in case of short linked lists, but might bring some speedup in case of very long linked lists.

Note: lets assume editing of nodes is not allowed, or better yet lets assume we are dealing with an immutable linked list.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top