1. Definition of stack:
The stack, as a data structure, is a special linear table that can only be inserted and deleted at one end. It stores data according to the principle of last-in, first-out, the first data is pushed into the bottom of the stack, the final data at the top of the stack, when the data needs to be read from the top of the stack to eject the data (the last data is read out first). The stack has a memory function, and the stack's insertion and deletion operations do not need to change the bottom pointer. Stacks are special linear tables that allow insertions and deletions on the same side. One end of the allowed insert and delete operations is called the top of the stack (top), the other end is the bottom of the stack (bottom), the stack bottom is fixed, and the stack top floats, and the number of elements in the stack is zero, called the empty stack. Insertion is generally called a stack (PUSH), and deletion is called a fallback (POP). A stack is also called a LIFO table.
2.java code Implementation Stack array implementation:
Package test; Public classStack {Private intMaxSize;//the size of the stack Private inttop; Private Char[] arr; PublicStackintsize) {MaxSize=size; Top= -1; Arr=New Char[MaxSize]; } Public voidPushCharValue) {//Press-in dataarr[++top] =value; } Public CharPop () {//Popup Data returnarr[top--]; } Public CharPeek () {//access top of stack element returnArr[top]; } PublicBoolean isfull () {//is the stack full? returnMaxSize-1==top; } PublicBoolean isEmpty () {//whether the stack is empty returntop = =-1; }}
Using the stack to implement the flashback output of a string
Packagetest; Public classReverse {String input; PublicReverse (String input) { This. Input =input; } PublicString Doreverse () {stack S=NewStack (input.length ()); for(inti = 0; I < input.length (); i++) {S.push (Input.charat (i)); } String Output= ""; while(!S.isempty ()) {Output+=S.pop (); } returnoutput; }}
Test:
@Test Public void Fun () { Reverse R=new Reverse ("I am in the human State"); System.out.println (R.doreverse ()); }
Chained implementations:
Packagetest;Importjava.util.LinkedList; Public classStack1 {PrivateLinkedlist<object> A =NewLinkedlist<object>(); Public voidpush (Object o) {a.addfirst (o); } PublicObject Pop () {returnA.removefirst (); } PublicObject Peek () {returnA.getfirst (); } Public Booleanempty () {returnA.isempty (); }}
Java Code Implementation stack