Java Custom Stack Stack class and its application

Source: Internet
Author: User

A stack is a special container for storing objects that follows the principle of last-in-first-out (LAST-IN-FIRST-OUT,LIFO) when inserting and deleting objects. Java itself has its own stack class package, in order to achieve learning purpose has better understanding of stack stack, DIY Java Stack class is a good start to learn:

Self-built Java Stack class

Stack class:

 PackageCom.stack;ImportJava.util.ArrayList;ImportJava.util.Arrays;/** * Stack Class * @author ganyee * */ Public  class Stack {    //define capacity Constant:capacity    Private Static Final intCapacity =1024x768;//define Capacity    Private Static intcapacity;//define the top position of stacks    //top =-1 meaning that stack empty    Private Static inttop =-1;//basic Object class arrayObject[] Array;//initialize The capacity of stacks     Public Stack() { This. capacity = capacity; Array =NewObject[capacity]; }//get the size of the stack     Public int GetSize(){if(IsEmpty ()) {return 0; }Else{returnTop +1; }    }//get whether stack is empty     Public Boolean IsEmpty(){return(Top <0); }//get the top element of the stack     PublicObjectTop()throwsexceptionstackempty{if(IsEmpty ()) {Throw NewExceptionstackempty ("Stack is empty"); }returnArray[top]; }//push element to stack     Public void Push(Object Element)throwsexceptionstackfull{if(GetSize () = = capacity) {Throw NewExceptionstackfull ("Stack is full");    } array[++ Top] = element; }//pop element from stack     PublicObjectPop()throwsexceptionstackempty{if(IsEmpty ()) {Throw NewExceptionstackempty ("Stack is empty"); }returnArray[top--]; }//get The all elements of stacks     PublicStringgetallelements()throwsexceptionstackempty{string[] arr =NewString[top +1];if(!isempty ()) { for(inti =0; i < GetSize (); i + +) {Arr[i] = (String) array[i]; }        }returnArrays.tostring (arr); }}

Custom Exceptionstackempty exception classes (see related blogs about how to customize exception classes)

package com.stack;publicclass ExceptionStackEmpty extends Exception {    //Constructor    publicExceptionStackEmpty(){    }    //Define myself exception construct with parameters    publicExceptionStackEmpty(String string){        super(string);    }}

Custom Exceptionstackfull Exception Classes

package com.stack;publicclass ExceptionStackFull extends Exception {    //Constructor        publicExceptionStackFull(){        }        //Define myself exception construct with parameters        publicExceptionStackFull(String string){            super(string);        }}

Test class:

Packagecom. Stack;public class Stacktest {public static void main (string[] args) {//TODO auto-generated method stub Stac K stack= New Stack ();System. out. println(Stack. GetSize());System. out. println(Stack. IsEmpty());try {stack. Push(8);Stack. Push(3);Stack. Push(4);Stack. Push(7);Stack. Push(1);Stack. Push(8);Stack. Push(3);Stack. Push(4);Stack. Push(7);Stack. Push(1);System. out. println(Stack. GetSize());System. out. println(Stack. Top());System. out. println(Stack. Getallelements());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());System. out. println(Stack. Pop());} catch (Exceptionstackfull e) {//TODO auto-generated catch block E. Printstacktrace();}catch (Exceptionstackempty e) {//TODO auto-generated catch block E. Printstacktrace();}    }}

Test results:

0true101[8347183471]1743817438

Application of stacks: symbol matching

Below, we will use a stack structure S to scan the arithmetic expression from left to right, checking that the parentheses are
No match.
Suppose the arithmetic expression is X = "x0x1x2...xn-1", where XI can be a parenthesis, a constant, a variable name, or an arithmetic operator. I
Each of the symbols in X is checked in turn, and the non-bracket symbols can be ignored. If an opening parenthesis is encountered, it is pressed into the stack S, and if a closing parenthesis is encountered, the top symbol is popped and contrasted with the closing parenthesis. If a pair of parentheses is found to be mismatched, or if the stack is empty when the closing parenthesis is encountered, or if the entire expression is not empty after the scan, you can conclude that the parentheses do not match.
After all characters have been scanned according to the above rules, if the stack is empty, the parentheses are matched. If you follow the implementation of the front-facing stack, each push () and pop () operation requires only a constant time, so for an arithmetic expression of length n, the above algorithm needs to run O (n) time.
The pseudo-code description of the algorithm is shown in algorithm two. 1:

Package com.stack; Public  class matchclass {     Public Static BooleanMatch (StringStr) throws Exceptionstackfull, exceptionstackempty{stack stack =NewStack ();Str=Str. ReplaceAll (" ","");CharS for(inti =0; I <Str. length (); i + +) {if(Str. charAt (i) = =' ('||Str. charAt (i) = =' {'||Str. charAt (i) = =' [') Stack.push (Str. CharAt (i));Else{if(Stack.isempty ())return false;Else{s =Str. charAt (i);Switch(s) { Case ' ) ':if((Character) stack.pop ()! =' (')return false; Break; Case '} ':if((Character) stack.pop ()! =' {')return false; Break; Case '] ':if((Character) stack.pop ()! =' [')return false; Break; }                }            }        }if(Stack.isempty ()) {return true; }Else{return false; }    }}
Package com.stack; Public classParentmatch { Public Static void Main(string[] args) {Matchclass match =NewMatchclass ();//string str = "() ({})"; Match        //string str = "({) {}) {([() []]}";//match        //string str = "([]{)";//not match        //string str = ") ([()] {} ";//not matchString str ="([())]{}";//not Match        Try{if(!match. Match (str)) {System. out. println (str +": Not Macth"); }Else{System. out. println (str +": Macth"); }        }Catch(Exceptionstackfull e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Exceptionstackempty e) {//TODO auto-generated catch blockE.printstacktrace (); }    }}

Test results:

()({}): Macth()({}) {([()[]])}: Macth([]{):Not Macth)([()] {}:Not Macth([())]{}:Not Macth

Article reference: Data structure and algorithm (Java description) Deng Junhui
Reprint please indicate the source, thank you!
http://blog.csdn.net/github_27609763/article/details/46420149

Java Custom Stack Stack class and its application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.