0

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--;  }}
6
  • Please show the rest of your stack code so we can help you. Commented Apr 25, 2015 at 17:42
  • 1
    The first line in your question contradicts the rest of the lines. You say want to copy elements from a queue to a stack and then you say you haven't been able to keep the stack the way it is and still copy its elements to a queue. Kindly edit your question to remove this ambiguity. Do you want to copy from a stack to queue or queue to stack? Commented Apr 25, 2015 at 17:47
  • What Stack class are you talking about? Is it yours? If so, why doesn't it provide a way to iterate over its content without modifying it? Commented Apr 25, 2015 at 17:51
  • Cant you just get the iterator for the stack and iterate through them. This will not alter the stack? Commented Apr 25, 2015 at 18:02
  • I edited my mistake in the question. I hope it makes more sense now. Commented Apr 25, 2015 at 18:52

1 Answer 1

0

Q: I haven't been able to think of a way to keep the stack the way it is A:

A: That's because reading from a "classic" stack is destructive. "Reading" an element == removing that element from the stack.

TWO SOLUTIONS:

1) Modify your stack implementation so that you can "peek" each element

... or ...

2) Create a new stack containing all the elements from the first one.

Q: I ended up with this method ... Trying to push elements back is not an option because it'll do it backwards.

"A: This is a variation on "Option 2): above.

SOLUTION: Just create a new stack object, and push each element at the same time as you enqueue the element.

PS:

The standard JRE implementation of Stack includes peek() and search() methods. But I don't think they would help you here. If you wanted "Option 1)", you'd have to implement your own, custom stack.

================== UPDATE ==================

Note, too:

  1. You should always indent your methods, and indent your "if" and "loop" blocks within your methods.

  2. You should use "camel-case" (lower-case first letter) for your method names.

Here are the "official" Java coding conventions. They were useful in 1995; they're useful today:

http://www.oracle.com/technetwork/java/index-135089.html

There's actually a third option: Java's "Stack" happens to implement "iterator". Here's an example:

EXAMPLE CODE:

package com.testcopy;

import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import java.util.Stack;

public class TestCopy {

    public static void main (String[] args) {

        TestCopy app = new TestCopy ();
        app.run ();
    }

    public void run () {
        // Create and populate stack
        Stack<String> myStack = new Stack<String> ();
        mkData(myStack);

        // Copy to queue
        Queue<String> myQueue = new ArrayDeque<String> ();
        copyFromStack (myStack, myQueue);

        // Print 
        int i=0;
        for (String s : myQueue) {
            System.out.println ("myQueue[" + i++ + "]: " + s);
        }
    }

    @SuppressWarnings("unchecked")
    public void mkData (Stack stack) {
        stack.push("A");
        stack.push("B");
        stack.push("C");
        // Stack should now contain C, B, A
    }

    public void copyFromStack (Stack stack, Queue queue) {
        @SuppressWarnings("rawtypes")
        Iterator it = stack.iterator ();
        while (it.hasNext()) {
            queue.add(it.next());
        }
    }
}

EXAMPLE OUTPUT:

myQueue[0]: A
myQueue[1]: B
myQueue[2]: C
Sign up to request clarification or add additional context in comments.

5 Comments

What if the original stack is huge? What if you have limited memory to work with. Questions like these implicitly ask for an optimized solution.
And what if the original stack isn't huge or you do have sufficient memory? The point is: both "Option 1" and "Option 2" are applicable. Which to choose? "It depends". And remember: "Option 2 " involves just three extra lines: 1) Create the new stack, 2) push the elements, and 3) replace the old stack with the new stack once everything's been copied.
But what if Option 1 is not possible because the Stack class is third party? The point I am trying to make is that creating a copy of the stack is kind of common sense and I don't believe the OP would post a question if that was a probable solution.
Creating a new stack was first thought, but I was hoping I could find a way to avoid that.
Your solution was most helpful. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.