课程: Java Algorithms
今天就学习课程吧!
今天就开通帐号,24,700 门业界名师课程任您挑!
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…
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。
内容
-
-
-
-
-
What is a linked list?2 分钟 18 秒
-
(已锁定)
Using the built-in linked list data structure in Java4 分钟 16 秒
-
(已锁定)
Create a custom data structure for linked list algorithms3 分钟 32 秒
-
(已锁定)
Linked list algorithms: Delete back half of a linked list4 分钟
-
(已锁定)
Solution: Sum contents of a linked list1 分钟 36 秒
-
-
-
-
-