I want to do the same thing I did in this code for stack
how can i change it so it will be for queue? I don't want to use stack or LinkedList for that
public StackAsArray(){
this(new DynamicArray());
}
public boolean isEmpty() {
}
public void push(Object o) {
}
public Object pop() {
}
}
You just need to replace your push and pop methods with enqueue and dequeue methods.
enqueue adds elements to the end of the array, while dequeue will remove it from the beginning.
public class QueueAsArray implements Queue {
...
public void enqueue(Object o) {
arr.set(numOfElements, o);
numOfElements++;
}
public Object dequeue() {
if(isEmpty()) { // an empty check is a MUST
return null;
}
numOfElements = numOfElements - 1;
Object res = arr.get(0);
arr.set(0, null); // not 100% sure this works, but since this is a homework question, its upto you to figure out. The logic is to remove the 0th element.
return res;
}
}
Related
I have a class MyList with the following methods :
public class MyList{
ArrayList<Object> list;
MyList(int a, int b)
{
list = new ArrayList<Object>();
for(;a<=b;a++)
list.add(a);
}
public void add(int index, Object o)
{
list.add(index, o);
}
public Object remove(int index) throws isEmptyException
{
if(isEmpty())
throw new isEmptyException();
else
return list.remove(index);
}
public boolean isEmpty()
{
return list.isEmpty();
}
Here's my Class Queue. I have to implement the following methods using only the above methods from MyList.
public class Queue extends MyList{
public void enqueue(Object o)
{
//adds a new Object to the queue
}
public Object dequeue()
{
//removes the next Object from the queue and returns it
}
public boolean empty()
{
//Checks if the queue is empty
}
I don't really know where to start here, since I don't know the size of the queue. Can someone give me a hint how to solve this? Is a recursive method useful here?
Thanks in advance!
Call the add or remove inside the enqueue and dequeue methods of the Queue class, maintain a pointer to first and last.
public class Queue extends MyList {
private int index;
private int firstIndex;
Queue(int a, int b)
{
super(a, b);
}
public void enqueue(Object o)
{
add(o);
index++;
}
public Object deueue() throws Exception {
if(firstIndex == index || isEmpty()) {
firstIndex =0; index =0;
throw new Exception("");
}
else
return list.remove(++firstIndex);
}
public boolean isEmpty()
{
return list.isEmpty();
}
}
Im working on a LinkedListStack and have to print out for example "size".
here is my LinkedListStack:
public class LinkedListStack {
private class Element {
public Object value;
public Element next;
}
private Element top;
private int size=0;
public void push(Object o) {
Element e=new Element();
e.value=o;
e.next=top;
top=e;
size++;
}
public Object pop() {
if (top!=null) {
Object v=top.value;
top=top.next;
size--;
return v;
} else {
return null;
}
}
public boolean isEmpty(){
return top==null;
}
public int size() {
return size;
}
public Object get(int n) {
Element current=top;
int i=0;
while (i<n && current!=null) {
current=current.next;
i++;
}
if (current==null)
return null;
else
return current.value;
}
}
I know I have to use
System.out.println ("...");
and that i need a new class, let's call it Stacki. Is must contain a main method where i can use the methods and print them out. So that would be:
public class Stacki {
public static void main(String[] args) {
}
}
how do I put
public void size() {
System.out.println ("size is"+size());
}
in that class? Because i cannot use the block as such, an error occurs.
Thank you :)
You instantiate your other class within Stacki, like:
public class Stacki {
public static void main(String[]) {
LinkedListStack stack = new LinkedListStack();
System.out.println("size is: " + stack.size());
... then you probably add some elements, remove some, and whenever you want to:
System.out.println("size is: " + stack.size());
And hint: Stacki is a rather nothing-saying name. Better call that class LinkedListStackTester or something alike. Names always say what the thing they denote is about!
And finally: this is really basic stuff. It doesn't make much sense to create your own stack class, when you have no idea how to put that to use. In that sense: you probably want to spend some hours here and work yourself through those tutorials!
I tried to work this out but couldn't.
I need to implement a class which implements iterator and takes iterator as constructor parameter,
1)Need to return every 2nd hasnext
2)Need to return every 2nd next element
Basically I am trying to make use of given iterator received from constructor, But when i use next element on hasnext I am actually increasing the iterator by one element. so problem comes when i independently access hasNext or next element and does not pass all the test cases. Any solution or idea on this
Template and my expected implementation looks like below:
public class AlternateIterator<T> implements Iterator<T>
public AlternateIterator(Iterator<T> target)
public boolean hasNext() {
boolean returnvalue = false;
if(iterator.hasNext()) {
iterator.next();
returnvalue = iterator.hasNext();
}
return returnvalue;
}
#Override
public T next() {
T object = null;
if(iterator.hasNext()) {
object = iterator.next();
return object;
}
else
return null;
-- Gone through this link but it creates a new implementation itself while i want to use the given template only:
Can we write our own iterator in Java?
Track whether you've skipped the element from the source iterator or not, like this:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
final class AlternateIterator<T>
implements Iterator<T>
{
static <T> Iterable<T> alternate(Iterable<T> original)
{
return () -> new AlternateIterator<>(original.iterator());
}
private final Iterator<T> source;
private boolean skipped;
AlternateIterator(Iterator<T> source)
{
this.source = Objects.requireNonNull(source);
}
#Override
public boolean hasNext()
{
if (!skipped) {
if (source.hasNext())
source.next();
skipped = true;
}
return source.hasNext();
}
#Override
public T next()
{
if (hasNext()) {
skipped = false;
return source.next();
}
throw new NoSuchElementException();
}
#Override
public void remove()
{
source.remove();
}
}
You need to have a boolean member which stores if hasNext has been called since the last call of next.
This way you know if you need to call an additional next or not in both methods.
Your issue is that hasNext() changes the state of the decorated Iterator. You need a member variable like skipped to track state so that hasNext() won't double-advance and skip two, and your implementation of next() should use this.hasNext(), not iterator.hasNext().
Edit: it'll look something like this:
public class AlternateIterator<T> implements Iterator<T> {
public AlternateIterator(Iterator<T> target) { ... }
private volatile boolean skipped = false;
public boolean hasNext() {
if (!skipped) {
skipped = true;
if (iterator.hasNext()) {
iterator.next();
}
}
return iterator.hasNext();
}
#Override
public T next() {
hasNext();
skipped = false;
return iterator.next();
}
}
I'm writing an ArrayStack class that uses an iterator. I know using an iterator for a stack doesn't necessarily make sense but this is for homework purposes. I am having trouble with the remove method. I understand its description but I'm having trouble implementing it. Here is the inner class of my program:
private class StackIterator implements Iterator<Item> {
private int index;
private boolean canremove;
public StackIterator() {
index = size - 1;
canremove = false;
}
#Override
public boolean hasNext()
{
return index > 0;
}
#Override
public Item next()
{
if (!hasNext()) {
throw new NoSuchElementException("There is no next element"+
" in the stack.");
}
canremove = true;
return contents[--index];
}
#Override
public void remove() {
if (!canremove) {
throw new IllegalStateException("Can only remove an element"
+ "after a call to the next method has been made.");
}
canremove = false;
}
}
How do I actually go about removing the element? Do I just decrease size? Or do I need more variables to keep track? Any help is appreciated.
The goal is to develop a java program to implement a Dqueue in an efficient manner for all the 6 methods below. I have to Extend java.util.LinkedList to Dqueue and implement all of the methods below.
public void enqueHead(E element),
public void enqueTail(E element)
public E dequeHead()
public E dequeTail()
public E peekHead() that returns the element at the Head but not remove it.
public E peekTail() that returns the element at the Tail but not remove it.
I have come up with the following code:
import java.util.LinkedList;
public class Dqueue<E> extends LinkedList<E> {
public void enqueHead(E element) {
if (isEmpty()) {
add(element);
return;
}
add(0, element);
}
public void enqueTail(E element) {
add(element);
}
public E dequeHead() {
if (isEmpty()) {
return null;
}
return remove(0);
}
public E dequeTail() {
if (isEmpty()) {
return null;
}
return remove(size() - 1);
}
public E peekHead() {
if (isEmpty()) {
return null;
}
return get(0);
}
public E peekTail() {
if (isEmpty()) {
return null;
}
return get(size() - 1);
}
}
I know that A double ended queue is much like a queue except that the operations of enqueing (adding) and dequeing (removing) can be done at both ends of the queue. In a conventional queue, the enque operation is done at the tail and deque is done at the tail but in a Dqueue these operations are allowed at both ends. My only question is if I am doing this correctly? Because it feels a little too simple for it to be right.