Learn about Java for a while and summarize the ' stacks ' that have been learned in the last few courses.
About Stacks
Stack is a special linear table that can only be inserted and deleted at one end.
It has a ' last in, first out (LIFO) ' feature.
About the Stack class
Stack class inherits Vector class
The following table is a few ways to stack classes
| Boolean |
empty()
Tests whether the stack is empty. |
| E |
peek()
View the object at the top of the stack, but not remove it from the stack. |
| E |
pop()
Removes the object at the top of the stack and returns the object as the value of this function. |
| E |
push(E item)
Press the item onto the top of the stack. |
| Int |
search(Object o)
Returns the position of the object in the stack, with a base of 1. |
Instance
Here I'm going to use arrays to implement stacks
PS: I use Java generics here, about Java generics in the previous essay I have introduced.
1 Importjava.util.Arrays;2 3 Public classMystack<e> {4 5 //create a new array of length 06 Privateobject[] src =NewObject[0];7 8 //press data into the stack9 Public voidpush (E s) {Ten //copy src array, length is the length of the original array +1 OneE[] e = (e[]) arrays.copyof (SRC, src.length + 1); A //Passes the incoming data to the last element of the new array -E[E.LENGTH-1] =(E) s; -src =e; the } - - //view data at the top of the stack - PublicE Peek () { + //returns the last element of the SRC array - return(E) src[src.length-1]; + } A at //eject data from the top of the stack [remove] - PublicE Pop () { - //Copy the SRC array to the new array to make it easier to eject the data at the top of the stack -E[] sr =(e[]) src; -E[] e = (e[]) arrays.copyof (SRC, src.length-1); -src =e; in return(E) sr[sr.length-1]; - } to + //get the length of the stack - Public intsize () { the returnsrc.length; * } $ Panax Notoginseng //determine if the stack is empty - Public Booleanempty () { the returnSrc.length = = 0; + } A the Public Static voidMain (string[] args) { +Mystack<string> st =NewMystack<string>(); - $ //press data into the stack $St.push ("AA"); -St.push ("BB"); -St.push ("CC"); theSt.push ("DD"); - Wuyi //output stack Top data theSYSTEM.OUT.PRINTLN ("The data at the top of the stack is:" +St.peek ()); - Wu //the length of the output stack -System.out.println ("The length of the stack is:" +st.size ()); About $ //when the stack is not empty, pop up the stack top data - while(!St.empty ()) { -System.out.println ("Popup Data:" +St.pop ()); - } A } +}
Operation Result:
The data at the top of the stack is: DD stack length: 4 Popup data: DD Popup data: CC popup data: BB Popup data: AA
Results analysis
Follow the stack ' LIFO ' feature, enter AA, BB, CC, DD, eject DD, CC, BB, AA.
Based on this feature, stacks are essential at some point.
Stacks in Java