课程: Java Algorithms

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Solution: Sum contents of a linked list

Solution: Sum contents of a linked list - Java教程

课程: Java Algorithms

Solution: Sum contents of a linked list

- [Instructor] Let's implement the sum function. We'll start off by creating a variable called sum to keep track of the sum of our items in the linked list. We'll also want a variable for keeping track of where we are in the list. We'll create a variable called current and set it to the beginning of the list. With our variables set up, now it's time to iterate through the list, adding each item's value to the sum. We can do this with a while loop. While the current item is not equal to null, we'll want to retrieve its data, add it to the sum, and then go to the next item in the list. We can access the nodes data with the val field. Then we'll add it to the sum. To increment the current variable, we can set current equal to current.next. That'll set us to the next element in the list. After iterating through the entire list, we can return the sum. That's the implementation. Looking at our test code, the sum would…

内容