Java使用Deque实现堆栈的方法
程序员文章站
2024-03-05 18:53:01
本文实例讲述了java使用deque实现堆栈的方法。分享给大家供大家参考。具体如下:
import java.util.arraydeque;
import j...
本文实例讲述了java使用deque实现堆栈的方法。分享给大家供大家参考。具体如下:
import java.util.arraydeque; import java.util.deque; public class integerstack { private deque<integer> data = new arraydeque<integer>(); public void push(integer element) { data.addfirst(element); } public integer pop() { return data.removefirst(); } public integer peek() { return data.peekfirst(); } public string tostring() { return data.tostring(); } public static void main(string[] args) { integerstack stack = new integerstack(); for (int i = 0; i < 5; i++) { stack.push(i); } system.out.println("after pushing 5 elements: " + stack); int m = stack.pop(); system.out.println("popped element = " + m); system.out.println("after popping 1 element : " + stack); int n = stack.peek(); system.out.println("peeked element = " + n); system.out.println("after peeking 1 element : " + stack); } } /* 输出 after pushing 5 elements: [4, 3, 2, 1, 0] popped element = 4 after popping 1 element : [3, 2, 1, 0] peeked element = 3 after peeking 1 element : [3, 2, 1, 0] */
希望本文所述对大家的java程序设计有所帮助。