Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Is there a way I can change the method switchPairs() to do the same it does but differently? JAVA public class LinkedList implements Iterable {

Is there a way I can change the method switchPairs() to do the same it does but differently? JAVA

public class LinkedListextends Comparable> implements Iterable{

private ListNode front; // first value in the list

private ListNode back; // last value in the list

private int size; // current number of elements

public LinkedList() {

front = new ListNode(null);

back = new ListNode(null);

clear();

}

}

public void switchPairs() {

int i=0;

while(i

if(!nodeAt(i+1).equals(front)) { //don't try to switch if the next node is the back of the list

ListNode current = nodeAt(i+1);

remove(i+1);

add(i,current.data);

i=i+2;

}

}

private ListNode nodeAt(int index) {

ListNode current;

if (index < size / 2) {

current = front;

for (int i = 0; i < index + 1; i++) {

current = current.next;

}

} else {

current = back;

for (int i = size; i >= index + 1; i--) {

current = current.prev;

}

}

return current;

}

private class LinkedIterator implements Iterator {

private ListNode current; // location of next value to return

private boolean removeOK; // whether it's okay to remove now

// post: constructs an iterator for the given list

public LinkedIterator() {

current = front.next;

removeOK = false;

}

// post: returns true if there are more elements left, false otherwise

public boolean hasNext() {

return current != back;

}

// pre : hasNext()

// post: returns the next element in the iteration

public E next() {

if (!hasNext()) {

throw new NoSuchElementException();

}

E result = current.data;

current = current.next;

removeOK = true;

return result;

}

// pre : next() has been called without a call on remove (i.e., at most

// one call per call on next)

// post: removes the last element returned by the iterator

public void remove() {

if (!removeOK) {

throw new IllegalStateException();

}

ListNode prev2 = current.prev.prev;

prev2.next = current;

current.prev = prev2;

size--;

removeOK = false;

}

}

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Security

Authors: Alfred Basta, Melissa Zgola

1st Edition

1435453905, 978-1435453906

More Books

Students also viewed these Databases questions

Question

What is the basis for Security Concerns in Cloud Computing?

Answered: 1 week ago

Question

Describe the three main Cloud Computing Environments.

Answered: 1 week ago