Stack简单实现向下增长数组版
2017-03-24 17:52
267 查看
格式和ArrayList类似,只是删除了一些不必要的方法。
public class LowStack<AnyType> {
private static final int DEFAULT_CAPACITY=10;//定义初始长度
private int theSize;//当前位置
private AnyType[] theItems;
public LowStack(){
doClear();
}
public void clear(){
doClear();
}
private void doClear(){
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){
return theSize;
}
public boolean isEmpty(){
return size()==0;
}
public void trimToSize(){//设置数组长度刚好为当前所用长度
ensureCapacity(size());
}
public AnyType peek(){//返回栈底元素
if(size()>0){
return theItems[size()-1];
}else{
return null;
}
}
@SuppressWarnings("unchecked")
public void ensureCapacity(int newCapacity){//重新分配存储单元
if(newCapacity<theSize)
return ;
AnyType[] old=theItems;
theItems=(AnyType[])new Object[newCapacity];//泛型数组的创建时非法的
for(int i=0;i<size();i++)//重新赋值
theItems[i]=old[i];
}
public boolean push(AnyType x){
add(size(),x);
return true;
}
public void add(int idx,AnyType x){
theItems[idx]=x;
theSize++;
}
public AnyType pop(){
AnyType removedItem=theItems[size()-1];
theSize--;
return removedItem;
}
}
测试用例
// LowStack<Integer> a=new LowStack<>();
// a.push(1);
// a.push(2);
// a.push(3);
// a.push(4);
// System.out.println(a.peek());
// while(!a.isEmpty()){
// System.out.println(a.pop());
// }
public class LowStack<AnyType> {
private static final int DEFAULT_CAPACITY=10;//定义初始长度
private int theSize;//当前位置
private AnyType[] theItems;
public LowStack(){
doClear();
}
public void clear(){
doClear();
}
private void doClear(){
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){
return theSize;
}
public boolean isEmpty(){
return size()==0;
}
public void trimToSize(){//设置数组长度刚好为当前所用长度
ensureCapacity(size());
}
public AnyType peek(){//返回栈底元素
if(size()>0){
return theItems[size()-1];
}else{
return null;
}
}
@SuppressWarnings("unchecked")
public void ensureCapacity(int newCapacity){//重新分配存储单元
if(newCapacity<theSize)
return ;
AnyType[] old=theItems;
theItems=(AnyType[])new Object[newCapacity];//泛型数组的创建时非法的
for(int i=0;i<size();i++)//重新赋值
theItems[i]=old[i];
}
public boolean push(AnyType x){
add(size(),x);
return true;
}
public void add(int idx,AnyType x){
theItems[idx]=x;
theSize++;
}
public AnyType pop(){
AnyType removedItem=theItems[size()-1];
theSize--;
return removedItem;
}
}
测试用例
// LowStack<Integer> a=new LowStack<>();
// a.push(1);
// a.push(2);
// a.push(3);
// a.push(4);
// System.out.println(a.peek());
// while(!a.isEmpty()){
// System.out.println(a.pop());
// }
相关文章推荐
- 算法导论------------栈(stack)简单的数组实现
- 用C#实现简单的控件数组
- C简单实现动态2维数组
- C语言中实现数组的动态增长
- C++用数组和链表分别实现Stack
- C++用数组和链表分别实现Stack
- C++ : 用proxy Class实现简单的二维数组。
- C#中定义数组和一个简单排序算法实现。
- strcat,strcpy,strcmp,strlen4个常用字符串处理函数的数组与指针简单实现方法~
- C语言使用数组实现简单队列
- 简单的桶式排序-基于数组的实现
- c#简单实现一个螺旋数组
- PHP 简单数组排序实现代码
- C#实现一个图形的动态效果(简单矩形不断向下运动的实现简单步骤)
- 1.数据结构(C语言)---自定义数组的简单实现
- 常见内部排序算法 简单数组实现与分析(快速(偶原创partition函数,望众高手指正)、归并、希尔、插入、选择、冒泡)
- 用数组实现一个简单的堆栈
- 用C#实现简单的控件数组
- Stack(栈)的简单应用——实现单词逆序
- 简单的桶式排序-基于数组的实现