栈的Java语言实现

时间:2021-10-02 15:34:17
【文件属性】:

文件名称:栈的Java语言实现

文件大小:12KB

文件格式:DOCX

更新时间:2021-10-02 15:34:17

栈 java

栈的顺序存储结构及Java实现 //MyStack.java public class MyStack { int MAX_SIZE = 100; int top; String[] stack; public void init(String[] array){ stack = new String[100]; top = -1; for (int i = 0; i < array.length; i++) { stack[i] = array[i]; top = i; } } public boolean push(String pusher){ if (top > MAX_SIZE) { return false; }else { top = top + 1; stack[top] = pusher; return true; } } public String pop(){ if (top == -1) { return "Error"; }else { String poper = stack[top]; stack[top]=null; top = top - 1; return poper; } } public void displayStack(){ for (int i = 0; i <=top; i++) { System.out.print(stack[i]+" "); } System.out.println(); } public static void main(String args[]){ String[] array = {"1","2","3"}; MyStack myStack = new MyStack(); myStack.init(array); myStack.displayStack(); myStack.push("4"); myStack.displayStack(); myStack.pop(); myStack.pop(); myStack.displayStack(); } }


网友评论