JAVA Data Structure ----- stack, java -----
Stack is a subclass of Vector, which implements a standard post-import, first-out stack.
Stack only defines the default constructor to create an empty stack. In addition to all the methods defined by the Vector, the stack also defines its own methods.
Five common stack methods:
Boolean empty (): test whether the stack is empty.
Object peek (): view the top element of the stack, but do not remove it.
Object pop (): return the top element of the stack and remove it.
Object push (object element): Inbound Stack
Int search (object element): returns the elements of an object in the stack, based on 1.
import java.util.*;public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } }}
stack: [ ]push(42)stack: [42]push(66)stack: [42, 66]push(99)stack: [42, 66, 99]pop -> 99stack: [42, 66]pop -> 66stack: [42]pop -> 42stack: [ ]pop -> empty stack