【数据结构】栈-数组的实现
2014-11-06 00:47
134 查看
首先是定义栈的基本结构,因为用数组实现
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;
}
然后是判空操作,想想为什么空的时候 TOP是0
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;
}
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;
}
然后是判空操作,想想为什么空的时候 TOP是0
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;
}
相关文章推荐
- 数据结构复习:队列-Java数组实现
- 数据结构-实现数组
- 巧用javascript数组实现数据结构-堆栈与队列
- C++数据结构--用向量数组实现大(小)根堆的插入和删除
- (1)数据结构——线性表(数组)实现
- 用C#编程语言实现数据结构传递整型变量、字符串和数组的方法
- 数据结构-用数组实现栈
- 【C++数据结构学习笔记---线性表】用数组实现线性表
- 数据结构:队列(循环数组实现)
- 数据结构之list(用数组实现)
- 重学数据结构004――栈的基本操作及实现(数组实现)
- 0元素数组实现变长TLV数据结构
- javascript的数组实现数据结构中的堆栈和队列
- 【C++数据结构学习笔记---栈】用数组实现栈
- C++类模板 实现两栈共享数组空间的算法 《数据结构》(北京科海) 自己摘抄完成
- javascript中数组Array对象调用不同的方法可以实现几种数据结构
- 数据结构: 图的数组表示实现
- 数据结构队列之环形队列的动态数组实现:queue
- php的哈希(实现数组的数据结构)
- 典型数据结构:线性表(基于数组的实现)