List achieve stack structure

Stack is an implementation of "last in, first out" data structure algorithms, stack feature is last out.
We use java in the List collection to implement a stack data structure.
Package com.prolog.api.webservicetest; / * 
 * @auther wind juvenile 
 * @mail [email protected] 
 * @date 2020-01-02 11:41 
 * @notify 
 * @version 1.0 
 * / 

Import of java.util.ArrayList ;
 Import java.util.Arrays;
 Import java.util.List; 

public  class Stack {
     Private the ArrayList <String> = stackList new new the ArrayList <> (); 

    // add elements to the stack 
    public  void the Add (String ... integers) { 
        List <String> integers1 = Arrays.asList (integers); 
        stackList.addAll(integers1);
    } 

    // pop the top element
    public String popup () {
         IF (stackList.size () == 0 ) {
             return "-1" ; 
        } 
        return stackList.remove (stackList.size () -. 1 ); 
    } 

    // return the top element, not pop 
    public getTop String () {
         iF (stackList.size () == 0 ) {
             return "-1" ; 
        } 
        return stackList.get (stackList.size () -. 1 ); 
    } 

    // determines whether the stack is empty 
    public  Boolean isEmpty ( ) {
         return stackList.isEmpty (); 
    }

    // returns the number of elements in the stack 
    public Integer getSize () {
         return stackList.size (); 
    } 

    // empty stack 
    public  void clearStack () { 
        stackList.clear (); 
    } 
}
View Code

Note that, when popped, and get the top element, it is necessary to determine whether there are elements within the stack, otherwise it will throw an exception.

Stack of applications

1 to determine whether a character from the string appear in pairs.

    // scenario: Let brackets must appear in pairs. Cancel each other with a stack 
    @Test
     public  void T1 () throws Exception { 
        Stack Stack = new new Stack (); 
        String STR = "(A + B) * (AC)" ;
         // loop string 
        for ( int I = 0; I <str.length (); I ++ ) {
             // get each element of the string 
            string S = String.valueOf (str.charAt (I));
             IF (s.equals ( "(")) { // if is (the push 
                stack.add (S); 
            } the else  IF (s.equals ( ")")) {// If) it is determined whether the current element stack, then there is no problem if 
                IF (stack.isEmpty ()) { 
                    System.out.println ( "invalid string" );
                     return ; 
                } the else { // there are elements of the current stack may only be (then pop 
                    stack.popup (); 
                } 
            } 
        } 
        System.out.println ( "legal string" ); 
    }
View Code

 

Guess you like

Origin www.cnblogs.com/zumengjie/p/12133370.html
Recommended