954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Reversing a Stack

Ok so I have to write a reverse method of a stack and I am not quite sure how to do it. I understand that i need to pop the strings from one stack into another but whenever I try to do this errors arise. Specifically it says it cannot find the pop method which is clearly defined above. Can anyone help with this problem?

import java.io.*;
import java.util.*;
  
  public class MyStack<E> implements MyStackInterface<E> {
    
    private List<E> theData;
    
    public MyStack() {
      theData = new ArrayList<E>();
    }
    
    Stack<String> theDataReversed = new Stack<String>();
    
    public E push(E o) {
    theData.add(o);
    return o;
  }
  
  public E peek() {
    if(empty()){
      throw new EmptyStackException();
    }
    return theData.get(theData.size() - 1);
  }
  
  public E pop() {
    if(empty()) {
      throw new EmptyStackException();
    }
      return theData.remove(theData.size() - 1);
    }
    
  public boolean empty() {
    return theData.size() == 0;
  }
  
  public MyStack<E> reverse() {

    while(theData.size() != 0){
      theDataReversed.add(0, theData.pop());
    }
    }
  }
nwalser
Newbie Poster
13 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

theData is a List. You should just need to call pop()

cale.macdonald
Junior Poster
153 posts since Jun 2009
Reputation Points: 16
Solved Threads: 31
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: