【数据结构】栈-数组的实现
发布时间:2020-12-15 06:04:51 所属栏目:安全 来源:网络整理
导读:首先是定义栈的基本结构,因为用数组实现 private String[] stack;private int TOP = 0; 然后是构造方法 StackOfStrings(int capacity) {stack = new String[capacity];} 然后是push,注意,TOP永远指向的是压入元素的后一位。 public void push(String str)
首先是定义栈的基本结构,因为用数组实现 private String[] stack; private int TOP = 0; 然后是构造方法 StackOfStrings(int capacity) { stack = new String[capacity]; } 然后是push,注意,TOP永远指向的是压入元素的后一位。 public void push(String str) { if (TOP == stack.length) // if full,increase the stack size resize(2 * stack.length); stack[TOP++] = str; } 然后是pop public String pop() { String popItem = stack[--TOP]; // if equal to 1/4,decrease the stack size if (TOP > 0 && TOP == stack.length / 4) resize(stack.length / 2); return popItem; }
public boolean isEmpty() { return TOP == 0; } 最后附上resize的代码 public void resize(int capacity) { String[] temp = new String[capacity]; for (int i = 0; i < TOP; i++) temp[i] = stack[i]; stack = temp; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |