import java.util.Iterator; public class customDSLL<Item> implements Iterable<Ite
ID: 3742945 • Letter: I
Question
import java.util.Iterator;
public class customDSLL<Item> implements Iterable<Item>{
private Node front;
private Node back;
private class Node{
/*
* TO DO
* Inner class
*/
}
public boolean isEmpty() {
/*
* TO DO
* return true if the DS is empty, else return false
*/
return true;
}
public int size() {
/*
* TO DO
* return the size of the DS, i.e the number of elements in the DS. Can you do it in constant time?
*/
return 0;
}
public void insertFront(Item it) {
/*
* TO DO
* Insert a new element at the front pointer.
*/
}
public void insertBack(Item it) {
/*
* TO DO
* Insert a new element at the back pointer.
*/
}
public Item removeFront() {
/*
* TO DO
* Remove a new element from the front pointer.
*/
return null;
}
public Item removeBack() {
/*
* TO DO
* Remove a new element from the back pointer.
*/
return null;
}
public Iterator<Item> iterator() {
/*
* TO DO
* Implement the iterator to enable usage of "foreach" loop.
*/
return null;
}
}
Explanation / Answer
import java.util.Iterator; public class customDSLL implements Iterable{ private Node front = null; private Node back = null; private class Node{ private Item item; private Node next; public Node(Item item) { this.item = item; next = null; } } public boolean isEmpty() { return front == null; } public int size() { int count = 0; Node temp = front; while (temp != null) { count++; temp = temp.next; } return count; } public void insertFront(Item it) { Node node = new Node(it); node.next = front; front = node; if(back == null) { back = front; } } public void insertBack(Item it) { Node node = new Node(it); back.next = node; back = node; if(front == null) { front = back; } } public Item removeFront() { Item it = front.item; front = front.next; if(front == null) { back = null; } return it; } public Item removeBack() { Item it = back.item; if(front == back) { front = null; back = null; } else { Node temp = front; while (temp.next.next != null) { temp = temp.next; } temp.next = null; back = temp; } return it; } public Iterator iterator() { return new Iterator() { Node temp = front; @Override public boolean hasNext() { return temp != null; } @Override public Item next() { Item item = temp.item; temp = temp.next; return item; } }; } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.