/** * Author: Joanna Klukowska * Date: Sept. 16, 2013 * * Implements LinkedList class for the second * class example - naive implementation. * This is iterative implementation of the methods. * The list is stored in unsorted order. * This version is still NOT correct although it fixes * some of the errors of the first version. */ package csci102_linked_list; public class LinkedList2 { final double ZERO = 0.0000000001; Node head; //reference to the first Node in the list /* * Class constructor */ public LinkedList2() { head = null; } /* * Inserts a node with valueToAdd at the end of the list. */ public void insertAtEnd ( double valueToAdd ) { //create Node with the new value Node nodeToAdd = new Node(); nodeToAdd.number = valueToAdd; nodeToAdd.link = null; Node current = head; //if the list is empty add the node at the head if (current == null) { head = nodeToAdd; return; } //otherwise look for the last element in the list while ( current.link != null ) { current = current.link ; } current.link = nodeToAdd ; } /* * Computes and returns the number of nodes in the list. */ public int size () { int numOfNodes = 0; Node current = head; //if the list is empty return zero if (current == null) { return numOfNodes; } //increment the counter for the first node and //look for the last element in the list do { current = current.link ; numOfNodes++; } while ( current != null ); return numOfNodes; } /* * Tests if valueToFind is on the list and returns true or * false accordingly. */ public boolean find ( double valueToFind ) { Node current = head; //if the list is empty return false if (current == null) { return false; } //otherwise look for the valueToFind in the list do { if ( Math.abs( current.number - valueToFind ) < ZERO ) return true; current = current.link ; } while ( current != null ); return false; } /* * Produces a String object based on the entire list, one * value per line (this may not be practical for long lists). */ public String toString() { String listInString = ""; Node current = head; //if list is empty, return an empty string if (current == null) return listInString; //process the list do { listInString += String.format("%.5f\n", current.number ); current = current.link ; } while ( current != null ); return listInString; } /* * Removes valueToRemove if it exists, otherwise returns false. */ public boolean remove( double valueToRemove) { //check if the value is there, if not, return false if (! find (valueToRemove) ) return false; //otherwise locate the value and remove it Node current = head; //look for the valueToRemove while ( current.link != null ) { if ( current.link.number == valueToRemove ) { //bypass the Node with the valueToRemove current.link = current.link.link; break; } current = current.link ; } return true; } }