Processing of Linked Lists in Java

·

2 min read

From Eck, D. J. (2020). Introduction to programming using Java, version 8.1.2 Hobart and William Smith Colleges. math.hws.edu/javanotes:

If head is a variable of type Node that points to the first node in the list, then the general form of the code for processing all the items in a linked list is:

Node runner;    // A pointer that will be used to traverse the list.
runner = head;  // Start with runner pointing to the head of the list.
while ( runner != null ) {     // Continue until null is encountered.
   process( runner.item );     // Do something with the item in the current node.
   runner = runner.next;       // Move on to the next node in the list.
} // Eck, 2020

The while loop can be replaced with the following for loop:

for ( Node runner = head; runner != null; runner = runner.next ) {
   process( runner.item );
}

If head is a variable of type IntNode that points to a linked list of integers, we can find the sum of the integers in the list using:

int sum = 0;
IntNode runner = head;
while ( runner != null ) {
   sum = sum + runner.item;   // Add current item to the sum.
   runner = runner.next;
}
System.out.println("The sum of the list of items is " + sum);
// Eck, 2020