栈的实现
作者:互联网
package com.practice; import com.practice.Array.Array; public class ArrayStack<E> implements Stack<E> { Array<E> arrayStack; public ArrayStack(int capacity){ arrayStack = new Array<>(capacity); } public ArrayStack(){ arrayStack = new Array<>(); } @Override public int getSize(){ return arrayStack.getSize(); } @Override public boolean isEmpty(){ return arrayStack.isEmpty(); } public int getCapacity(){ return arrayStack.getCapacity(); } @Override public void push(E e){ arrayStack.addLast(e); } @Override public E pop(){ return arrayStack.removeLast(); } @Override public E peek(){ return arrayStack.getLast(); } @Override public String toString(){ StringBuilder res = new StringBuilder(); res.append("Stack :"); res.append('['); for(int i = 0;i < arrayStack.getSize();i ++){ res.append(arrayStack.get(i)); if(i != arrayStack.getSize() - 1){ res.append(", "); } } res.append("] top"); return res.toString(); } }
package com.practice; import com.practice.Array.Array; public class Main { public static void main(String[] args) { // write your code here ArrayStack<Integer> stack = new ArrayStack<>(); for(int i = 0; i < 5; i ++){ stack.push(i); System.out.println(stack); } stack.pop(); System.out.println(stack); } }
Stack :[0] top Stack :[0, 1] top Stack :[0, 1, 2] top Stack :[0, 1, 2, 3] top Stack :[0, 1, 2, 3, 4] top Stack :[0, 1, 2, 3] top
标签:实现,res,top,public,arrayStack,Array,Stack 来源: https://www.cnblogs.com/oneJavaWorkerStudy/p/16468027.html