首页 > 代码库 > 【DataStructure】The description and usage of Stack

【DataStructure】The description and usage of Stack

A stack is collection that implements the last-in-first-out protocal.This means that the only access object in the collections is the last one thatwas inserted.The fundamental  operations of a stack are: add an element onto the top of stack, access the current elments on the top of the stack and remove the current element on the top of stack.Now we first view the defination in the java framework. 

public class Stack<E> extends Vector<E> {
    /**
     * Creates an empty Stack.
     */
    public Stack() {
    }

but  in the comments of this method: 

 * <p>A more complete and consistent set of LIFO stack operations is
 * provided by the {@link Deque} interface and its implementations, which
 * should be used in preference to this class.  For example:
 * <pre>   {@code
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>

The example about string stack which is inited by deque, the source is coppied from the book. 

package com.albertshao.ds.stack;

//  Data Structures with Java, Second Edition
//  by John R. Hubbard
//  Copyright 2007 by McGraw-Hill

import java.util.*;

public class TestStringStack {
  public static void main(String[] args) {
    Deque<String> stack = new ArrayDeque<String>();
    stack.push("GB");
    stack.push("DE");
    stack.push("FR");
    stack.push("ES");
    System.out.println(stack);
    //peek:Retrieves, but does not remove
    System.out.println("stack.peek(): " + stack.peek());
    System.out.println("stack.pop(): " + stack.pop());
    System.out.println(stack);
    System.out.println("stack.pop(): " + stack.pop());
    System.out.println(stack);
    System.out.println("stack.push(\"IE\"): ");
    stack.push("IE");
    System.out.println(stack);
  }
}

/*  Output:
[ES, FR, DE, GB]
stack.peek(): ES
stack.pop(): ES
[FR, DE, GB]
stack.pop(): FR
[DE, GB]
stack.push("IE"): 
[IE, DE, GB]
*/