{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

set1_sol

# set1_sol - CS112 Spring 2011 Problem Set 1 Linked Lists 1...

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

CS112 Spring 2011: Problem Set 1 Linked Lists ------------------------------------------------------------------------ 1. Given the following definition of a linked list class: public class Node<T> { public T data; public Node<T> next; public Node(T data, Node<T> next) { this.data = data; this.next = next; } } public class LinkedList<T> { private Node<T> front; ... } Implement a method in the LinkedList class that will search the linked list and return the number of occurrences of a given target item: public int numberOfOccurrences(T target) { /* COMPLETE THIS METHOD */ } *SOLUTION* public int numberOfOccurrences(T target) { int count=0; for (Node ptr=front;ptr != null;ptr=ptr->next) { if (target.equals(ptr.data)) { count++; } return count; } ------------------------------------------------------------------------ 2. * In the same LinkedList class as in the previous problem, implement a method that will delete all occurrences of a given target item: public void deleteAllOccurrences(T target) { /* COMPLETE THIS METHOD */ } *SOLUTION* public void deleteAllOcurrences(T target) { if (front == null) { return; } Node<T> curr=front, prev=null; while (curr != null) { if (curr.data.equals(target)) {

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

View Full Document
if (prev == null) { // target is the first element front = curr.next;
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 3

set1_sol - CS112 Spring 2011 Problem Set 1 Linked Lists 1...

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

View Full Document
Ask a homework question - tutors are online