From the course: Nail Your Java Interview

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

Solution: Delete the Middle of a Linked List

Solution: Delete the Middle of a Linked List - Java Tutorial

From the course: Nail Your Java Interview

Solution: Delete the Middle of a Linked List

(upbeat music) - [Instructor] Let's implement the sum function. We'll start off by creating a variable called sum to keep track of the sum of the 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, 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 in the linked list is not equal to null, we'll want to retrieve its data, add it to the sum, and go to the next item in the list. We can access a node's data with the val field, then we'll add it to the sum. We'll also want to increment the current variable, so we move along in the linked list. We'll set current = current.next. Once we've iterated through the list, we can return the sum.

Contents