首页 > 代码库 > 【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] */
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。