I'm supposed to copy elements from a stack to a queue.
I haven't been able to think of a way to keep the stack the way it is and still copy its elements to a queue.
I ended up with this method which removes the elements completely from the stack and adds them to the queue:
public void CopyFromStack(){
E t;
int c = w.size();
while(c != 0){
t = w.pop();
enqueue(t);
c--; }}
Trying to push elements back is not an option because it'll do it backwards.
Edit: This is the class that contains my method which is my queue class:
public class Queue<E> {
protected int size;
protected Node<E> head;
protected Node<E> tail;
NodeStack<E> w = new NodeStack<E>();
NodeStack<E> w2 = new NodeStack<E>();
public Queue(){
size = 0;
head = tail = null;}
public boolean isEmpty(){
return size==0;}
public void enqueue(E elem) {
Node<E> node = new Node<E>();
node.setElement(elem);
node.setNext(null);
if (size == 0) head = node;
else tail.setNext(node);
tail = node;
size++; }
public E dequeue() {
if (size == 0) System.out.print("Queue is empty.");
E tmp = head.getElement();
head = head.getNext();
size--;
if (size == 0) tail = null;
return tmp; }
public String toString(){
String s = "";
E t;
int c = size;
while(c != 0){
t = dequeue();
s += t + " ";
enqueue(t);
c--; }
return s;}
public int FindItem(E elem){
int index=0;
int c = size;
E t;
while(c != 0){
t = dequeue();
if (t == elem)
return index;
else index++;
c--;}
System.out.print("Not found!");
return -1;}
public void CopyToStack(){
System.out.print("Elements copied to the stack are: ");
E t;
int c = size;
while(c != 0){
t = dequeue();
w.push(t);
enqueue(t);
c--;
System.out.print(w.pop()+" "); }}
public void CopyFromStack(){
E t;
int c = w.size();
while(c != 0){
t = w.pop();
enqueue(t);
c--; }}
stackcode so we can help you.