Home > Blockchain >  reverse a stack array without changing the original stack in java
reverse a stack array without changing the original stack in java

Time:01-15

I want to returns a new stack that contains the same elements as the given stack, but in reversed order, and leaves the given stack in its original state I wrote this code but its not working.

    public class Stack {
    private char []mysatck;  
    int maxSize;
    int top; 

    Stack(int size) {
    this.mysatck=new char[size];
    this.maxSize=size;
    this.top=-1;
    }

    char push(char x){
       if (isFull()!=true) {
            top  ;
            mysatck[top]=x; 
            return x;
        }  
    return 0;
    }
   
     char pop(){       
         if (isEmpty()==true) {
                    
             return 0;
         }else{
         char temp=mysatck[top];
         top--;
         return temp;
     } }
       

     int top(){
     return top;
     }    
     
     
    Stack reversed(){  
        Stack s=new Stack(5);     
        if (isEmpty()!=true) {    
           
            for (int i = 0; i <= top(); i  ) {
                s.push(pop());
                
            }           
           }
      return s;
    }
    
  public String toString(){
      String element="";
      for (int i = 0; i <=top(); i  ) {
          element = mysatck[i] " ";
      }          
      return element;
   }
    
}

could you please help me solve my problem

CodePudding user response:

First of all, welcome to StackOverflow! Your code is dealing with a lot of non-idempotent operations that are not treated as such. For example, top() will change as the original stack changes, but it is used as the upper bound of the for loop. pop() will also modify the current stack by removing the top element. Since you have access to the stack's underlying array, you can simply just iterate through that in reverse order and push the contents onto the new stack. For example,

Stack reversed() {
    Stack reversedStack = new Stack(mystack.length);
    for (int i = top; i >= 0; i--) {
        reversedStack.push(mystack[i])
    }
    return reversedStack;
}

You may have to adjust the code, because I don't fully understand the semantics of top in your design. Notice how we don't use any operations that modify the original stack since we rely on the stack's underlying array. Also, here is a reference to read more about iterating backwards through arrays.

  •  Tags:  
  • Related