Java data structures - stack

class MyStack {
     // stack bottom we use an array to store the data 
    int [] Elements; 

    public MyStack () { 
        Elements = new new  int [0 ]; 
    } 

    // pressed element 
    public  void Push ( int Element) {
         // create a new array 
        int [] = newArr new new  int [elements.length +. 1 ];
         // the copy source elements of the array into a new array 
        for ( int I = 0; I <elements.length; I ++ ) { 
            newArr [I ] = Elements [I]; 
        }
        // the element to be added into the new array 
        newArr [elements.length] = Element;
         // the new array replaces the old array 
        Elements = newArr; 
    } 

    // remove the top element 
    public  int POP () {
         // stack no element 
        IF (elements.length == 0 ) {
             the throw  new new a RuntimeException ( "Stack iS empty" ); 
        } 
        // remove the last element of the array 
        int element elements = [-elements.length. 1 ];
         // Create a new array 
        int [] = newArr new new  int [-elements.length. 1 ];
        // the original array except the last element of the other elements are copied to the new array 
        for ( int I = 0; I <-elements.length. 1; I ++ ) { 
            newArr [I] = Elements [I]; 
        } 
        // replace the old array using the new array 
        elements = newArr;
         // return the top element 
        return element; 
    } 

    // Check the top element 
    public  int PEEK () {
         // stack no element 
        IF (elements.length == 0 ) {
             the throw  new new a RuntimeException ( "Stack IS empty" ); 
        } 
        return Elements [elements.length. 1-]; 
    } 

    // determines whether the stack is empty 
    public  Boolean isEmpty () {
         return elements.length == 0 ; 
    } 
} 

public  class the Main {
     public  static  void main (String [] args) {
         // create a stack 
        MyStack MS = new new MyStack (); 

        // pressed into data 
        ms.push (. 9 ); 
        ms.push ( . 8 ); 
        ms.push ( . 7 ); 

        // remove the top element
         // System.out.println (ms.pop ()) ; 
        
        // Check the top element
        System.out.println (ms.peek ()); 
        ms.pop (); 
        System.out.println (ms.peek ()); 

        // determines whether the stack is empty 
        System.out.println (ms.isEmpty () ); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/GjqDream/p/11590554.html