java集合框架之堆栈

来源:互联网 发布:蛇口招商网络怎么样 编辑:程序博客网 时间:2024/06/05 20:30

    堆栈是一种“后进先出”的数据结构,只在一端进行输入或输出。

    java.util包中的Stack<E>泛型类创建一个堆栈对象,调用public E push(E item)实现压栈操作,调用public E pop()实现出栈操作。

    其他方法:public e peek()获取栈顶数据,但不删除该数据; public int Search(Object data)获取数据在堆栈中的位置,最顶端的位置时1,向下依次增加,如果不含此数据,返回-1;public boolean Empty(),判断是否有数据。

    使用堆栈可以节省内存的开销。的比如递归是一种很消耗内存的算法,可以借助堆栈消除大部分递归。

    下面以斐波那契数列计算为例,对比计算第40个斐波那契数列数字所花费的时间。


package 斐波那契数列_堆栈法与递归法比较;import java.util.*;public class Main {static int recursion(int n){if(n==1)return 1;if(n==2)return 1;elsereturn recursion(n-1)+recursion(n-2);}static int stack(int n){Stack<Integer> stack=new Stack<Integer>();stack.push(new Integer(1));stack.push(new Integer(1));int k=3;while(k<=n){Integer F1=stack.pop();int f1=F1.intValue();Integer F2=stack.pop();int f2=F2.intValue();Integer t=new Integer(f1+f2);stack.push(t);stack.push(F2);k++;}stack.pop();return stack.pop();}public static void main(String[] args) {Scanner in=new Scanner(System.in);int n=in.nextInt();in.close();long time;long st;long et;long value;st=System.currentTimeMillis();value=recursion(n);et=System.currentTimeMillis();System.out.println("斐波那契数列递归法"+value+"    耗时"+(et-st));st=System.currentTimeMillis();value=stack(n);et=System.currentTimeMillis();System.out.println("斐波那契数列堆栈法"+value+"    耗时"+(et-st));}}//40//斐波那契数列递归法102334155    耗时369//斐波那契数列堆栈法102334155    耗时0


0 0
原创粉丝点击