/** * Author: Joanna Klukowska * Date: Sept. 15, 2013 * * Implements LinkedList class for the first * class example - naive implementation. * This is iterative implementation of the methods. * The list is stored in unsorted order. * This version is NOT correct and in fact * will not pass most of the tests you would care to * write! * */ package csci102_linked_list; public class LinkedList { Node head; //reference to the first Node in the list /* * Class constructor */ public LinkedList() { head = new Node(); head.link = null; head.number = 0.0; } /* * 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; //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; //look for the last element in the list while ( current.link != null ) { current = current.link ; numOfNodes++; } return numOfNodes; } /* * Tests if valueToFind is on the list and returns true or * false accordingly. */ public boolean find ( double valueToFind ) { Node current = head; //look for the valueToFind in the list while ( current.link != null ) { if ( current.number == valueToFind ) return true; current = current.link ; } 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; //look for the last element in the list while ( current.link != null ) { listInString += String.format("%.20f\n", current.number ); current = current.link ; } 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 do { if ( current.link.number == valueToRemove ) { //bypass the Node with the valueToRemove current.link = current.link.link; break; } current = current.link ; } while ( current != null ); return true; } }