Data Structures question- JAVA

Anonymous
timer Asked: Jun 23rd, 2018
account_balance_wallet $30

Question description

In this lab you will explore two implementations of the ADT list. The first implementation will use an array and the second will use a linked structure. In both cases you will create new methods that work directly with the implementations. You will implement a reverse method that will reverse the order of the items in the list. You will also implement a cycle method that will move the first item in the list to the last position. The java files are attached as word documents since I cannot attach a .java file.

import java.io.*; /** A linked implementation of the ADT List. * * This code is from Chapter 14 of * Data Structures and Abstractions with Java 4/e * @author Frank M. Carrano * * Modifications were made by Charles Hoot: * The toString method is overwritten to give a nice display of the items in * the list in this format { <1> <2> <3> <4> } * * An alternate display method has been created to print the list one item * to a line along with the index * * Stubs were added for the methods needed to complete Lab 13 * * @version 4.0 */ class LList implements ListInterface { private Node firstNode; // Reference to first node of chain private int numberOfEntries; public LList() { initializeDataFields(); } // end default constructor public void clear() { initializeDataFields(); } // end clear // Initialize the class's data fields to indicate an empty list. private void initializeDataFields() { firstNode = null; numberOfEntries = 0; } public void add(T newEntry) { Node newNode = new Node(newEntry); if (isEmpty()) { firstNode = newNode; } else // Add to end of nonempty list { Node lastNode = getNodeAt(numberOfEntries); lastNode.setNextNode(newNode); // Make last node reference new node } // end if numberOfEntries++; } // end add public void add(int newPosition, T newEntry) { if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) { Node newNode = new Node(newEntry); if (newPosition == 1) // Case 1 { newNode.setNextNode(firstNode); firstNode = newNode; } else // Case 2: List is not empty { // and newPosition > 1 Node nodeBefore = getNodeAt(newPosition - 1); Node nodeAfter = nodeBefore.getNextNode(); newNode.setNextNode(nodeAfter); nodeBefore.setNextNode(newNode); } // end if numberOfEntries++; } else { throw new IndexOutOfBoundsException("Illegal position given to add operation."); } } // end add public T remove(int givenPosition) { T result = null; // Teturn value if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); if (givenPosition == 1) // Case 1: remove first entry { result = firstNode.getData(); // Save entry to be removed firstNode = firstNode.getNextNode(); // Remove entry } else // Case 2: Not first entry { Node nodeBefore = getNodeAt(givenPosition - 1); Node nodeToRemove = nodeBefore.getNextNode(); result = nodeToRemove.getData(); // Save entry to be removed Node nodeAfter = nodeToRemove.getNextNode(); nodeBefore.setNextNode(nodeAfter); // Remove entry } // end if numberOfEntries--; // Update count return result; } else throw new IndexOutOfBoundsException("Illegal position given to remove operation."); } // end remove public boolean contains(T anEntry) { boolean found = false; Node currentNode = firstNode; while (!found && (currentNode != null)) { if (anEntry.equals(currentNode.getData())) { found = true; } else { currentNode = currentNode.getNextNode(); } } // end while return found; } // end contains public T getEntry(int givenPosition) { if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); return getNodeAt(givenPosition).getData(); } else throw new IndexOutOfBoundsException("Illegal position given to getEntry operation."); } // end getEntry public T replace(int givenPosition, T newEntry) { if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); Node desiredNode = getNodeAt(givenPosition); T originalEntry = desiredNode.getData(); desiredNode.setData(newEntry); return originalEntry; } else throw new IndexOutOfBoundsException("Illegal position given to replace operation."); } // end replace public int getLength() { return numberOfEntries; } public boolean isEmpty() { boolean result; if (numberOfEntries == 0) // Or getLength() == 0 { assert firstNode == null; result = true; } else { assert firstNode != null; result = false; } // end if return result; } // end isEmpty public T[] toArray() { // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] result = (T[]) new Object[numberOfEntries]; int index = 0; Node currentNode = firstNode; while ((index < numberOfEntries) && (currentNode != null)) { result[index] = currentNode.getData(); currentNode = currentNode.getNextNode(); index++; } // end while return result; } // end toArray // Return a reference to the node at a given position. // Precondition: List is not empty; // 1 <= givenPostion <= numberOfEntries private Node getNodeAt(int givenPosition) { assert (firstNode != null) && (1 <= givenPosition) && (givenPosition <= numberOfEntries); Node currentNode = firstNode; // Traverse the chain to locate the desired node for (int counter = 1; counter < givenPosition; counter++) { currentNode = currentNode.getNextNode(); } assert currentNode != null; return currentNode; } // end getNodeAt private class Node { private T data; // entry in bag private Node next; // link to next node private Node(T dataPortion) { this(dataPortion, null); } // end constructor private Node(T dataPortion, Node nextNode) { data = dataPortion; next = nextNode; } // end constructor private T getData() { return data; } // end getData private void setData(T newData) { data = newData; } // end setData private Node getNextNode() { return next; } // end getNextNode private void setNextNode(Node nextNode) { next = nextNode; } // end setNextNode } // end Node /** Build a string representation of the list. * * @return A string showing the state of the list. */ public String toString() { String result = "{ "; Node currentNode = firstNode; while (currentNode != null) { result = result + "<" + currentNode.data + "> "; currentNode = currentNode.next; } result = result + "}"; return result; } /** Display the list with indices one to a line * This will correctly display an infinite list, * whereas the toString() method will never return. * */ public void display() { int index = 1; Node currentNode = firstNode; while (currentNode != null) { System.out.println(index + ":" + currentNode.getData()); currentNode = currentNode.getNextNode(); index++; } } // end display /** Check to see if two lists are the same. * @param aList Another linked list to check this list against. * @return True if all the items in this list and the other list are equals. */ public boolean equals(LList aList) { boolean isEqual = false; // result of comparison of lists Node currOne = firstNode; Node currTwo = aList.firstNode; int counter; if (numberOfEntries == aList.numberOfEntries) { // Lists have equal lengths, so traverse both and compare items as you go: // (NOTE: loop is skipped if lists are empty) while ((currOne != null) && (currOne.getData()).equals(currTwo.getData())) { currOne = currOne.getNextNode(); currTwo = currTwo.getNextNode(); } // end while // If we made it to the end, the lists are equal isEqual = (currOne == null); } return isEqual; } // end equals /********************************************************************* * * METHODS TO BE COMPLETED * ***********************************************************************/ /** Reverse the order of items in a list. */ public void reverse() { // CODE TO BE COMPLETED } /** Cycle the first item to the end of the list. */ public void cycle() { // CODE TO BE COMPLETED } }
/** * This class performs tests on the extensions to the AList class. * * @author Charles Hoot * @version 4.0 */ public class ArrayListExtensionsTest { private static AList testList1 = new AList(); private static AList testList2 = new AList(); private static AList testList3 = new AList(); private static AList testList4 = new AList(); private static AList testList5 = new AList(); private static AList testList6 = new AList(); private static AList testList7 = new AList(); private static AList testList8 = new AList(); private static AList testList9 = new AList(); private static AList testList10 = new AList(); private static AList testList11 = new AList(); private static AList testList12 = new AList(); private static AList testList13 = new AList(); private static AList testList14 = new AList(); private static AList testList15 = new AList(); private static AList testList16 = new AList(); private static AList testList17 = new AList(); public static void main(String args[]) { checkReverse(); checkCycle(); } public static void initializeLists() { testList1.clear(); testList1.add("Jack"); testList1.add("Jill"); testList1.add("John"); testList2.clear(); testList2.add("Jack"); testList2.add("Jill"); testList2.add("John"); testList3.clear(); testList3.add("Jill"); testList3.add("John"); testList3.add("Jack"); testList4.clear(); testList4.add("Jack"); testList4.add("Jill"); testList5.clear(); testList5.add("Jack"); testList5.add("John"); testList5.add("Jill"); testList6.clear(); testList6.add("John"); testList6.add("Jack"); testList6.add("Jill"); testList7.clear(); testList7.add("A"); testList7.add("B"); testList7.add("C"); testList7.add("D"); testList7.add("E"); testList7.add("F"); testList8.clear(); testList8.add("F"); testList8.add("E"); testList8.add("D"); testList8.add("C"); testList8.add("B"); testList8.add("A"); testList9.clear(); testList9.add("A"); testList9.add("B"); testList9.add("C"); testList9.add("D"); testList9.add("E"); testList9.add("F"); testList9.add("G"); testList10.clear(); testList10.add("G"); testList10.add("F"); testList10.add("E"); testList10.add("D"); testList10.add("C"); testList10.add("B"); testList10.add("A"); testList11.clear(); testList11.add("Jill"); testList11.add("John"); testList11.add("Jack"); testList11.add("Jerry"); testList12.clear(); testList12.add("Jill"); testList12.add("Jack"); testList12.add("John"); testList12.add("Jerry"); testList13.clear(); testList13.add("Jill"); testList13.add("Jack"); testList13.add("Jerry"); testList13.add("John"); testList14.clear(); testList15.clear(); testList16.clear(); testList16.add("Jill"); testList17.clear(); testList17.add("Jill"); System.out.println(); } public static void checkReverse() { initializeLists(); System.out.println("TESTING REVERSE"); System.out.println("List 1 is "); testList1.display(); System.out.println("Reversing list one"); testList1.reverse(); System.out.println("List 1 is now"); testList1.display(); System.out.println("Reversing list one a second time"); testList1.reverse(); if(testList1.equals(testList2)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list result)"); testList1.display(); } System.out.println(); System.out.println("Reversing a list twice"); testList1.reverse(); testList1.reverse(); if(testList1.equals(testList2)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list result)"); testList1.display(); } System.out.println(); System.out.println("Reversing list 7 of even length"); testList7.reverse(); if(testList7.equals(testList8)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list on reverse)"); testList7.display(); } System.out.println(); System.out.println("Reversing list 9 of odd length"); testList9.reverse(); if(testList9.equals(testList10)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list on reverse)"); testList10.display(); } System.out.println(); System.out.println("Reversing a list of length 0"); testList14.reverse(); if(testList15.equals(testList14)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list on reverse)"); testList14.display(); } System.out.println(); System.out.println("Reversing a list of length 1"); testList16.reverse(); if(testList17.equals(testList16)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list on reverse)"); testList16.display(); } System.out.println(); } public static void checkCycle() { initializeLists(); System.out.println("TESTING CYCLE"); System.out.println("Cycling list 1 once"); testList1.cycle(); if(testList1.equals(testList3)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list result)"); testList1.display(); } System.out.println(); System.out.println("Cycling list 3 three times"); testList3.cycle(); testList3.cycle(); testList3.cycle(); if(testList1.equals(testList3)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list result)"); testList3.display(); } System.out.println(); System.out.println("Cycle a list of length 0"); testList14.reverse(); if(testList15.equals(testList14)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list on cycle)"); testList14.display(); } System.out.println(); System.out.println("Cylce a list of length 1"); testList16.reverse(); if(testList17.equals(testList16)) System.out.println(" Passed test"); else { System.out.println("*** Failed test (bad list on cycle)"); testList16.display(); } System.out.println(); } }
/** An interface for the ADT list. * Entries in the list have positions that begin with 1. * * This code is from Chapter 12 of * Data Structures and Abstractions with Java 4/e * by Carrano */ public interface ListInterface { /** Adds a new entry to the end of this list. Entries currently in the list are unaffected. The list's size is increased by 1. * @param newEntry The object to be added as a new entry. */ public void add(T newEntry); /** Adds a new entry at a specified position within this list. * Entries originally at and above the specified position * are at the next higher position within the list. * The list's size is increased by 1. * @param newPosition An integer that specifies the desired * position of the new entry. * @param newEntry The object to be added as a new entry. * @throws IndexOutOfBoundsException if either * newPosition less than 1, or * newPosition greater than getLength()+1. */ public void add(int newPosition, T newEntry); /** Removes the entry at a given position from this list. * Entries originally at positions higher than the given * position are at the next lower position within the list, * and the list's size is decreased by 1. * @param givenPosition An integer that indicates the position of * the entry to be removed. * @return A reference to the removed entry. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T remove(int givenPosition); /** Removes all entries from this list. */ public void clear(); /** Replaces the entry at a given position in this list. * @param givenPosition An integer that indicates the position of the * entry to be replaced. * @param newEntry The object that will replace the entry at the * position givenPosition. * @return The original entry that was replaced. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T replace(int givenPosition, T newEntry); /** Retrieves the entry at a given position in this list. * @param givenPosition An integer that indicates the position of * the desired entry. * @return A reference to the indicated entry. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T getEntry(int givenPosition); /** Sees whether this list contains a given entry. * @param anEntry The object that is the desired entry. * @return True if the list contains anEntry, or false if not. */ public boolean contains(T anEntry); /** Gets the length of this list. * @return The integer number of entries currently in the list. */ public int getLength(); /** Sees whether this list is empty. * @return True if the list is empty, or false if not. */ public boolean isEmpty(); /** Retrieves all entries that are in this list in the order in which they occur in the list. @return A newly allocated array of all the entries in the list. */ public T[] toArray(); } // end ListInterface
LLab 13 List Implementation Goal In this lab you will explore two implementations of the ADT list. The first implementation will use an array and the second will use a linked structure. In both cases you will create new methods that work directly with the implementations. You will implement a reverse method that will reverse the order of the items in the list. You will also implement a cycle method that will move the first item in the list to the last position. Resources • • • • Appendix A: Creating Classes from Other Classes Chapter 12: Lists Chapter 13: List Implementations That Use Arrays Chapter 14: A List Implementation That Links Data In javadoc directory • ListInterface.html—Interface documentation for the interface ListInterface Java Files • • • • • AList.java ArrayListExtensionsTest.java LList.java LinkedListExtensionsTest.java ListInterface.java Introduction As was seen in the last lab, a list is an ordered collection of elements supporting basic operations such as add and remove. One way to implement a list is to use an array. The other standard implementation is a linked structure. In this lab, you will take a working implementation of each basic type and create two new methods. If you have not done so already, take a moment to examine the code in AList.java. Consider the code that implements the add method. public void add(int newPosition, T newEntry) { checkInitialization(); if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) { if (newPosition <= numberOfEntries) { makeRoom(newPosition); } list[newPosition] = newEntry; numberOfEntries++; ensureCapacity(); // Ensure enough room for next add } else { throw new IndexOutOfBoundsException( "Illegal position given to add operation."); } } // end add Lab Manual for Data Structures and Abstractions with Java ™ 173 // Doubles the size of the array list if it is full. private void ensureCapacity() { int capacity = list.length - 1; if (numberOfEntries >= capacity) { int newCapacity = 2 * capacity; checkCapacity(newCapacity); // Is capacity too big? list = Arrays.copyOf(list, newCapacity + 1); } } // end ensureCapacity /** Makes room for a new entry at newPosition. * Precondition: 1 <= newPosition <= numberOfEntries+1; * numberOfEntries is list's length before addition. * checkInitialization has been called. */ private void makeRoom(int newPosition) { assert (newPosition >= 1) && (newPosition <= numberOfEntries + 1); int newIndex = newPosition; int lastIndex = numberOfEntries; // Move each entry to next higher index, starting at end of // array and continuing until the entry at newIndex is moved for (int index = lastIndex; index >= newIndex; index--) { list[index + 1] = list[index]; } } // end makeRoom Let's trace the last statement in the following code fragment. AList x = new AList(5); x.add("a"); x.add("b"); x.add("c"); x.add("d"); x.add(2, "x"); // trace this one The initial state of the object is numberOfEntries: 4 list: 0 "a" "b" "c" "d" 1 2 3 4 5 ... 25 The object has been initialized, so checkInitialization() returns. Since newPosition=2, the condition ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) is true. The condition newPosition <= numberOfEntries is also true, so we invoke the method makeRoom(2). 174 Lab 13 List Implementation We set the local variables newIndex to 2 and lastIndex to 4 resulting in the following state. newPosition: 2 newIndex: 2 lastIndex: 4 numberOfEntries: 4 list: 0 "a" "b" "c" "d" 1 2 3 4 5 ... 25 Now we do the for loop in makeRoom, we start index at lastIndex and then execute list[index + 1] = list[index]. We are in the following state. newPosition: 2 newIndex: 2 lastIndex: 4 index: 4 numberOfEntries: 4 list: 0 "a" "b" "c" "d" "d" 1 2 3 4 5 ... 25 We update the loop index by sutracting 1 and then compare the result with newIndex. Since 3 is >= 2, we continue with a second execution of the body of the loop. After it is done, we are in the following state. newPosition: 2 newIndex: 2 lastIndex: 4 index: 3 numberOfEntries: 4 list: 0 "a" "b" "c" "c" "d" 1 2 3 4 5 ... 25 Again,we update the loop index by sutracting 1 and then compare the result with newIndex. Since 2 is >= 2, we continue with a third execution of the body of the loop. After it is done, we are in the following state. newPosition: 2 newIndex: 2 lastIndex: 4 index: 2 numberOfEntries: 4 list: 0 "a" "b" "b" "c" "d" 1 2 3 4 5 ... 25 Again,we update the loop index by sutracting 1 and then compare the result with newIndex. Since 1 is not >= 2, we exit the loop and then return to add from the makeRoom method. Lab Manual for Data Structures and Abstractions with Java ™ 175 The next line in the add method puts newEntry into the array at newPosition. newPosition: 2 newEntry: "x" numberOfEntries: 4 list: 0 "a" "x" "b" "c" "d" 1 2 3 4 5 ... 25 The next line in the add method adjusts the number of entries. newPosition: 2 newEntry: "x" numberOfEntries: 5 list: 0 "a" "x" "b" "c" "d" 1 2 3 4 5 ... 25 Finally we invoke the ensureCapacity() method. The list.length is 26, so we set capacity to 25. The numberOfEnties is 5 and capacity is 26, so the condition numberOfEntries >= capacity is false. We return from the ensureCapacity() method. We return from the add method and the final state of our object is numberOfEntries: 5 list: 0 "a" "x" "b" "c" "d" 1 2 3 4 5 ... 25 Lets contrast this with the add method for the linked implementation of the list. public void add(int newPosition, T newEntry) { if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) { Node newNode = new Node(newEntry); if (newPosition == 1) // Case 1 { newNode.setNextNode(firstNode); firstNode = newNode; } else // Case 2: List is not empty { // and newPosition > 1 Node nodeBefore = getNodeAt(newPosition - 1); Node nodeAfter = nodeBefore.getNextNode(); newNode.setNextNode(nodeAfter); nodeBefore.setNextNode(newNode); } // end if numberOfEntries++; } else throw new IndexOutOfBoundsException( "Illegal position given to add operation."); } // end add 176 Lab 13 List Implementation Again we trace the last statement in the code fragment. LList x = new LList(); x.add("a"); x.add("b"); x.add("c"); x.add("d"); x.add(2, "x"); // trace this one The initial state of the object is numberOfEntries: 4 firstNode "a" "b" "c" "d" [4] The condition ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) is true. A new node is created. newPosition: 2 newEntry: "x" numberOfEntries: 4 firstNode "a" newNode "x" "b" "c" "d" The condition (newPosition == 1) is false since the insertion is not at the front of the list. The else branch is chosen. The local variable nodeBefore is set to getNodeAt(1). Then the variable nodeAfter is set. newPosition: 2 newEntry: "x" isSuccessful: true nodeBefore nodeAfter firstNode "a" "b" "c" "d" numberOfEntries: 4 newNode "x" [6] Lab Manual for Data Structures and Abstractions with Java ™ 177 The next reference for the new node is set to be the node after the insertion point. newPosition: 2 newEntry: "x" isSuccessful: true nodeBefore nodeAfter firstNode "a" "b" "c" "d" numberOfEntries: 4 newNode "x" [7] Finally, the new node is linked into the list by setting the next reference of the node before and the number of entries is updated. newPosition: 2 newEntry: "x" isSuccessful: true nodeBefore nodeAfter firstNode "a" newNode "x" "b" "c" "d" numberOfEntries: 5 The reverse operation is often supplied as a basic operation of a list. One example that we saw in the Advanced sorting lab was used to convert an array that was sorted from smallest to largest into an array that was sorted in the other direction. The cycle operation is less common, but can be used in a number of different applications. One example is a list of days in the week. At the start of the week, the list is (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday). As each day passes, the list will be cycled by moving the first item to the end of the list. At Sunday midnight, for example, the list will be cycled to (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday). To implement both the reverse and cycle methods, we will be using list surgery. As we saw with the linked representatin of the bag, the order that operations is done can be criticial. If you are not careful, the list will not survive the surgery. To avoid problems with surgery, it is always a good idea to trace carefully the intended operation of methods before implementing the code. 178 Lab 13 List Implementation Pre-Lab Visualization Array Reverse Suppose there is an array based list with the following state: numberOfEntries: 6 list: "a" "b" "c" "d" "e" "f" 1 2 3 4 5 6 ... 25 5 6 ... 25 0 What will the final state be after reverse()? numberOfEntries: list: 0 1 2 3 4 To reach the final state, follow these steps. Show the state of the list after each step. a. Swap the items in the first and last positions. numberOfEntries: list: 0 b. 1 2 3 4 5 6 ... 25 ... 25 ... 25 Swap the items in the second and second to last positions. numberOfEntries: list: 0 c. 1 2 3 4 5 6 Swap the items in the third and third to last positions. numberOfEntries: list: 0 1 2 3 4 5 6 To be general, a loop will be needed. Lab Manual for Data Structures and Abstractions with Java ™ 179 If there are n items in the list, what will be the indices of the first items in the swaps? What will be the indices of the second items in the swaps? Write an algorithm to implement reverse. 180 Lab 13 List Implementation Array Cycle Suppose there is a list with the following state: numberOfEntries: 4 list: "a" "b" "c" "d" 1 2 3 4 0 5 ... 25 What will the final state be after cycle()? numberOfEntries: 4 list: "a" "b" "c" "d" 1 2 3 4 0 5 ... 25 To reach the final state, follow these steps. Show the state of the list after each step. a. Remember the first item. numberOfEntries: 4 list: 0 b. "a" "b" "c" "d" 1 2 3 4 5 ... 25 5 ... 25 5 ... 25 Copy each item down one position. numberOfEntries: 4 list: 0 c. "a" "b" "c" "d" 1 2 3 4 Copy the remembered item to the last position. numberOfEntries: 4 list: 0 "a" "b" "c" "d" 1 2 3 4 Again, a loop will be needed. Lab Manual for Data Structures and Abstractions with Java ™ 181 If there are n items in the list, what are the indices of the items that are moved? What are the indices of the locations that the items are moved into? Write an algorithm to implement cycle. Linked Reverse The algorithm that will be used to reverse the linked chain is very different from the algorithm used with the array implementation. No swaps will be done, but instead the links will be altered in a single pass over the list. Suppose there is a list with the following state: numberOfEntries: 4 firstNode "a" "b" "c" "d" What will the final state be after reverse()? numberOfEntries: firstNode 182 "a" "b" "c" "d" Lab 13 List Implementation To reach the final state, follow these steps. Show the state of the list after each step. a. Start in the initial state. Use three variables to reference the first three nodes. (From now on, when refering to a position, it will be with respect to the order in the diagram). numberOfEntries: firstNode "a" "b" "c" "d" [20] b. Make the first node’s next reference be null. numberOfEntries: firstNode c. "a" "b" "c" "d" Make the second node’s next reference be the first node. Change all three reference variables so that they move forward by one in the picture. numberOfEntries: firstNode d. "a" "b" "c" "d" Make the third node’s next reference be the second node. Change all three reference variables so that they move forward by one in the picture. numberOfEntries: firstNode "a" "b" Lab Manual for Data Structures and Abstractions with Java ™ "c" "d" 183 e. Make the fourth node’s next reference be the third node. numberOfEntries: firstNode "a" "b" "c" "d" f. Change the variable firstNode so that it references the fourth node. numberOfEntries: firstNode "a" "b" "c" "d" To be general, a loop will be needed. Write an algorithm for the reverse operation. Consider each of the following cases and decide if the algorithm handles it correctly. i. ii. iii. 184 A list with no elements A list with one element A list with two elements Lab 13 List Implementation Linked Cycle Suppose there is a list with the following initial state: numberOfEntries: 4 firstNode "a" "b" "c" "d" What will the final state be after cycle()? (The first node is moved to the back of the list.) numberOfEntries: firstNode "a" "b" "c" "d" To reach the final state, we can follow these steps. Show the state of the list after each step. a. Start in the initial state. Create a variable that refers to the second node in the list. Find and then create a variable that refers to the last node in the list. numberOfEntries: firstNode b. "a" "b" "c" "d" Make the last node’s next reference be the first node. numberOfEntries: firstNode "a" "b" Lab Manual for Data Structures and Abstractions with Java ™ "c" "d" 185 c. Change the variable firstNode so that it references the second node. numberOfEntries: firstNode d. "a" "b" "c" "d" Make the former first node’s next reference be null. numberOfEntries: firstNode "a" "b" "c" "d" Write an algorithm for the cycle operation. Consider each of the following cases and decide if the algorithm handles it correctly. i. ii. iii. 186 A list with no elements A list with one element A list with two elements Lab 13 List Implementation Directed Lab Work The classes AList and LList are working implementations of the ListInterface.java. The methods you will be working on already exist but do not function yet. Take a look at that code now if you have not done so already. Array Reverse Step 1. is needed. In the reverse method of AList, implement your algorithm from the pre-lab exercises. Iteration Checkpoint: Compile and run ArrayListExtensionsTest. The checkReverse tests should pass. If not, debug and retest. Array Cycle Step 2. In the cycle method of AList, implement your algorithm from the pre-lab exercises. This method needs some form of iteration, but it may not be explicit. It can use the private methods of the AList class to avoid an explicit loop in the cycle method. Either way is acceptable. Checkpoint: : Compile and run ArrayListExtensionsTest. All tests should pass. If not, debug and retest. Linked Reverse Step 3. is needed. In the reverse method of LList, implement your algorithm from the pre-lab exercises. Iteration Checkpoint: Compile and run LinkedListExtensionsTest. The checkReverse tests should pass. If not, debug and retest. Linked Cycle Step 4. In the cycle method of LList, implement your algorithm from the pre-lab exercises. Final checkpoint: Compile and run LinkedListExtensionsTest. All tests should pass. If not, debug and retest. Lab Manual for Data Structures and Abstractions with Java ™ 187 Post-Lab Follow-Ups 1. Create test cases for the other methods in ListInterface. 2. In lists of size 10, 20 and 30, how many assignments are made using the list array by the reverse method in AList? How many times is the getNextNode method called by the reverse method in LList? (Include calls made directly by reverse or by helper methods like getNodeAt.) 3. In lists of size 10, 20 and 30, how many assignments are made using the list array by the cycle method? How many times is the getNextNode method called by the cycle method in LList? (Include calls made directly by reverse or by helper methods like getNodeAt.) 4. Implement the reverse method using only the public methods in ListInterface. Compare the performance with what you found in Questions 2 and 3. 5. Implement cycle method using only the public methods in ListInterface. performance with what you found in Questions 2 and 3. 6. Consider a method Compare the void randomPermutation() that will randomly reorder the contents of the list. Create three versions of the method and compare the performance as you did in Question 4. In the first version, only use the methods from ListInterface. In the second version, always work directly with the array list in the AList implementation. In the third version, always work directly with the linked chain in the LList implementation. 7. Consider a method void moveToBack(int from) that will move the item at position from to the end of the list. Create three versions of the method and compare the performance as you did in Question 4. In the first version, only use the methods from ListInterface. In the second version, always work directly with the array list in the AList implementation. In the third version, always work directly with the linked chain in the LList implementation. 8. Consider a method void interleave() that will do a perfect shuffle. Conceptually, you split the lists into halves and then alternate taking items from the two lists. For example, if the original list is [a b c d e f g h i], the splits would be [a b c d e] and [f g h i]. (If the length is odd, the first list gets the extra item.) The result of the interleave is [a f b g c g d i e]. Create three versions of the method and compare the performance as you did in Question 4. In the first version, only use the methods from ListInterface. In the second version, always work directly with the array list in the AList implementation. In the third version, always work directly with the linked chain in the LList implementation. 188 Lab 13 List Implementation

Tutor Answer

criss53
School: Rice University

Here i...

flag Report DMCA
Review

Anonymous
Excellent job

Similar Questions
Hot Questions
Related Tags

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors