Question

Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...

Java

implement the method in IteratorExercise.java using only list iterator methods:

bubbleSort: sort the provided list using bubble sort

Do not modify the test code in each function. You can look at that code for some ideas for implementing the methods.

import java.lang.Comparable;
import java.util.*;

public class IteratorExercise {
  
   public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {
       // first line to start you off
       ListIterator<E> iit = c.listIterator(), jit;

       /**** Test code: do not modify *****/
       List cc = new LinkedList(c);
       Collections.sort(c);
       ListIterator it1 = c.listIterator(), it2 = cc.listIterator();
    while (it1.hasNext()) {
      if (!it1.next().equals(it2.next()))
               throw new Exception("List not sorted");
    }
       /***********************************/
   }

public static <E> void reverseList(List<E> c) throws Exception {
       /**** Test code: do not modify *****/
       LinkedList cc = new LinkedList(c);
       /***********************************/

       // Reverse the list using iterators. Do not use List methods

   /**** Test code: do not modify *****/
       Iterator it1 = c.listIterator(), it2 = cc.descendingIterator();
       while (it1.hasNext()) {
      if (!it1.next().equals(it2.next()))
               throw new Exception("List not reversed");
    }
       /***********************************/
}

   public static <E> void removeEveryOtherElement(List<E> c) throws Exception {
       /**** Test code: do not modify *****/
       LinkedList cc = new LinkedList(c);
       /***********************************/

       // Remove every other element (starting with the second element:
       // all odd indices)

   /**** Test code: do not modify *****/
       printList(cc);
       printList(c);
       ListIterator it1 = c.listIterator(), it2 = cc.listIterator();
       while (it1.hasNext()) {
      if (!it1.next().equals(it2.next()))
               throw new Exception("Even indices not equal");
           if (!it1.hasNext()) break;
           if (it1.next().equals(it2.next()))
               throw new Exception("Odd index not removed");
           it1.previous();
    }
       /***********************************/
   }

   public static void printList(List c) {
       StringBuilder str = new StringBuilder();
       String sep = " ";
       for (Object i : c) {
           str.append(i);
           str.append(sep);
       }
       System.out.println(str.toString());
   }

   public static void fillList(List<Integer> c) {
       Random r = new Random();
       for (int i = 0; i < 23; i++) c.add(i);
       Collections.shuffle(c);
   }

   public static void main(String[] args) {
       try {
       List<Integer> lst = new ArrayList<Integer>();
       fillList(lst);

       bubbleSort(lst);

       removeEveryOtherElement(lst);

       reverseList(lst);
       } catch (Exception e) { System.err.println(e.getMessage()); }
   }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ANSWER:

OUTPUT:

CODE:

public static void removeEveryOtherElement(List c) throws Exception {
/*** Test code: do not modify ****/
LinkedList cc = new LinkedList(c);
/***********************************/

// Remove every other element (starting with the second element:
// all odd indices)
ListIterator it = c.listIterator();
while(it.hasNext()) {
it.next(); // even index
if(it.hasNext()) {
it.next(); //odd index
it.remove();
}
}

Add a comment
Know the answer?
Add Answer to:
Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

    iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not. Test by using the following code: LL<Integer> L = new LL<>(); for (int i = 1000; i > 0; i-=3) sl.add(i); try { L.insert(122, L.getNode(70), L.getNode(21)); if (L.detectLoop()) System.out.println("True"); else System.out.println("False."); } catch(Exception e){ e.printStackTrace(); } class Linkedlist<E>{ private static class Node<E>{ private E element; private Node<E> next; public Node(E e, Node<E> n){ element =...

  • Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...

    Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works: JstyArray<Integer> data; data = new JstyArray<Integer>(10); for (int i = 0; i < 10; ++i) { data.set(i, new Integer(i) ); } int sum = 0; for ( int v : data ) { if (v == null) continue; // empty cell sum += v; } The iterator provided by this class follows the behaviour of...

  • Write a unit test to test the following class. Using Java : //Test only the debit...

    Write a unit test to test the following class. Using Java : //Test only the debit method in the BankAccount. : import java.util.*; public class BankAccount { private String customerName; private double balance; private boolean frozen = false; private BankAccount() { } public BankAccount(String Name, double balance) { customerName = Name; this.balance = balance; } public String getCustomerName() { return customerName; } public double getBalance() { return balance; } public void setDebit(double amount) throws Exception { if (frozen) { throw...

  • java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then...

    java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then output comes like this 5 4 3 2 1 Stack is empty. here is the code that i'm going to use class Stack<T> implements Iterator<T> {    LinkedList<T> list;       public Stack() {        list = new LinkedList<T>();    }       public boolean isEmpty() {        return list.isEmpty();   ...

  • BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include...

    BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include the method to delete a node from the Linked List. In summary: 1) Add the method Delete 2) Method call to delete, with a number that IS in the list 3) Method call to delete, with a number that is NOT in the list - Be sure to include comments - Use meaningful identifier names (constants where appropriate) import java.io.*; 1/ Java program to...

  • Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...

    Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods. For Secondary class(es): Include a JavaDoc comment that describes the purpose of...

  • How to complete this methods: import java.io.FileInputStream; import java.io.FileNotFoundException; import java.time.Loc...

    How to complete this methods: import java.io.FileInputStream; import java.io.FileNotFoundException; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; /** * Utility class that deals with all the other classes. * * @author EECS2030 Summer 2019 * */ public final class Registrar {    public static final String COURSES_FILE = "Courses.csv";    public static final String STUDENTS_FILE = "Students.csv";    public static final String PATH = System.getProperty("java.class.path");    /**    * Hash table to store the list of students using their...

  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • 1. Implement Doubly Linked List get method which behaves like the operator [] of array. -...

    1. Implement Doubly Linked List get method which behaves like the operator [] of array. - It takes an integer parameter i as the index, it throw an Exception if the index i is illegal, returns the element at given index i, it traverse from the header of the list if index i is in the lower end of the list(less than half of the size), and traverse from the trailer of the list if index i is in the...

  • How to complete these methods: /**    * Returns a reference to the course with title equals to the argument. This    * m...

    How to complete these methods: /**    * Returns a reference to the course with title equals to the argument. This    * method searches in the courses stored in the HashMap {@code courses} to find    * the course whose title equals to the argument {@code title}. If the course is    * not found, {@code null} is returned.    *    * @param title the title of the course    * @return a reference to the course, or {@code null} if the course is not   ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT