# practiceLinkedList - would return 9 This solution uses a...

This preview shows pages 1–2. Sign up to view the full content.

CSE205- Fall 2008 Linked List Problems Last Name _________________First________________________Date____________ For each of these problems, assume you have a linked list of integer values and access to the beginning of the list. Each node has value and next instance variables. You may use any of the LinkedList methods from LinkedList.java, posted under “Code Examples” on the course web site. 1.Write a method sumAll that computes and returns the sum of all values in the list. For example, if the original list is: 1 2 3 4 5 this method would return 15. Answer: public int sumAll() { Node current = head; int sum = 0; while(current != null) { sum += current.value; current = current.next; } return sum; } 2.Write a method sumAlternate that computes and returns the sum of every other value in the list starting with the first one. For example, if the original list is: 1 2 3 4 5 this method

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: would return 9. /* This solution uses a boolean variable that alternates on every pass through the while loop in order to add up every other value. */ public int sumAlternate() { Node current = head; int sum = 0; boolean everyOther = true; while(current != null) { if(everyOther) { sum += current.value; everyOther = false; } else everyOther = true; current = current.next; } return sum; } 3.Write a method sumEvens that computes and returns the sum of all even numbers in the list. .For example, if the original list is: 1 2 3 4 5 this method would return 6. public int sumEvens() { Node current = head; int sum = 0; while(current != null) { if(current.value % 2 == 0) sum += current.value; current = current.next; } return sum; }...
View Full Document

## This note was uploaded on 06/11/2009 for the course CS 205214 taught by Professor Balasooriya/kouvetakis during the Spring '09 term at ASU.

### Page1 / 2

practiceLinkedList - would return 9 This solution uses a...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online