Pages

Tuesday, November 20, 2012

Arrays using stacks.

Hi all,

The following code is for implementing array structure using stacks.The implementation is not complete (it doesnt include runtime exception checkings etc) to focus more on logic rather than validations.

package algorithmProblems;

import java.util.Stack;

public class ArrayUsingStack {
   
   
    public static void main(String args[]){
    Array2 ar=new Array2(10);
   
    ar.disp();                       
    ar.set(11, 5);
    ar.disp();
   
    System.out.println(ar.get(4));
    }
}

class Array2{
   
    Stack s1,s2;
    Array2(int size){
        s1=new Stack();
        s2=new Stack();
        s1.setSize(size);
        s2.setSize(size);
        System.out.println(s1.size());
        for(int i=0;i<s1.size();i++){
            s1.set(i,i);/* instead you can create a method initialize and call it in constructor.. actually we shouldnt use this set method . I have used for clarity */
           
        }
}
   
    public void add(int value){
        s1.push(value);
    }
   
    public Object get(int index){
        int diff=s1.size()-index;
        int ret=0;
       
       
        for(int i=0;i<diff;i++){
           
            s2.push(s1.pop());
           
           
        }
        ret=(Integer)s1.peek();
        for(int i=0;i<diff;i++){
            s1.push(s2.pop());
        }
        return ret;
    }
   
    public void disp(){
        System.out.println(s1);
    }
   
    public void set(int index,int value){
       
        if(index>s1.size()){
            System.out.println("Array Index out of Bounds");
            return;
        }
        int diff=s1.size()-index;
        System.out.println(s1);
        for(int i=0;i<diff+1;i++){
            s2.push(s1.pop());
        }
        s1.push(value);
        for(int i=0;i<diff;i++){
            s1.push(s2.pop());
        }
       
       
       
    }
   
}
From the above program the logic is clear we need to copy some elements to another stack and perform the operation and then again push the elements back to original stack. You can add further operations/validations as an excercise.

No comments:

Post a Comment