简单数据结构实现——堆栈

来源:互联网 发布:钱学森 气功 知乎 编辑:程序博客网 时间:2024/06/06 08:47

堆栈 (Stack),最基本的数据结构之一,先进后出的FILO典型结构,主要操作有push(),pop(),top()方法,分别为压栈,出栈,返回栈顶元素。

在下面给出的代码实现中,增加了一些辅助的操作,包括size(), trim(), enlarge(), isEmpty(), toString()方法。

并且因为还没有系统的学习泛型,因此在这里给出的是基于int型的简单实现。运用泛型的通用实现将在以后补完。

Java代码实现:

public class Stack{private final double enlargeRatio=0.75;private final int DEFAULT_CAPACITY=10;private int idxOfTop=0;//Point to next usable position.private int capacity;private int[] stack;public Stack(){stack=new int[DEFAULT_CAPACITY];capacity=DEFAULT_CAPACITY;}public Stack(int capacity){stack=new int[capacity];this.capacity=capacity;}/*//Not sure if this constructor is correct!public Stack(Collection<? extends AnyType> c){capacity=c.length*2;stack=new AnyType[capacity];for(int i=0;i<c.length;i++){stack[i]=c[i];}idxOfTop=c.length;}*/public void push(int element){if(idxOfTop+1>=enlargeRatio*stack.length)enlarge();stack[idxOfTop]=element;idxOfTop++;}public void pop(){if(!isEmpty())idxOfTop--;else System.out.println("Stack is empty, can't pop!");}public int top(){if(!isEmpty())return stack[idxOfTop-1];else{System.out.println("Stack is empty, no top element!");return Integer.MIN_VALUE;}}public void trim(){capacity=size();int[] newStack=new int[capacity];for(int i=0;i<size();i++){newStack[i]=stack[i];}stack=newStack;}public int size(){return idxOfTop;}public boolean isEmpty(){if(idxOfTop==0) return true;else return false;}public String toString(){String str="";if(isEmpty()) return "This is an empty stack";else{str+="[";for(int i=0;i<size();i++){str=str+" "+stack[i];}str+=" ]";}return str;}//This method will doubly enlarge the stack.private void enlarge(){capacity*=2;int[] newStack=new int[capacity];for(int i=0;i<size();i++){newStack[i]=stack[i];}stack=newStack;}}


原创粉丝点击