栈的两种实现方法--数组实现与链式实现
来源:互联网 发布:学生手机兼职赚钱软件 编辑:程序博客网 时间:2024/06/06 16:36
栈(stack)是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈顶(top)。栈又叫做先进后出(Last In First Out)表。
栈通过push向栈输入,通过pop和top从栈中输出,只有栈顶元素可以访问。
栈有两种实现方法,一种是是通过数组实现,一种是链式实现。
数组实现代码如下:
public class ArrayStack<AnyType> { private AnyType []theArray; //存储空间基址private int topOfStack; //栈顶private static final int space=10; //数组容量public ArrayStack(){topOfStack=-1;increaseSpace(space);}public boolean isEmpty(){ //判断是否为空return topOfStack==-1;}public void push(AnyType x){ //压栈if(topOfStack>space)increaseSpace(space+1);topOfStack++;theArray[topOfStack]=x;}public AnyType pop() { //出栈if(topOfStack==-1)return null; AnyType a=theArray[topOfStack]; topOfStack--; return a;}public void increaseSpace(int space){ //扩容AnyType old[]=theArray;theArray=(AnyType []) new Object[space];for(int i=0;i<topOfStack+1;i++)theArray[i]=old[i];}public static void main(String[] args) { ArrayStack<Integer> as=new ArrayStack<Integer>(); as.push(1); as.push(2); as.push(3); as.push(4); System.out.println(as.pop()); System.out.println(as.pop()); System.out.println(as.pop()); System.out.println(as.pop()); System.out.println(as.pop()); }}
通过链式实现的代码如下:
public class SingleLinkedStack<AnyType> {private Node<AnyType> top;private int theSize;class Node<AnyType>{ //结点Node类 public AnyType data; public Node<AnyType> next; public Node(AnyType d,Node<AnyType> next ){ this.data=d; this.next=next; } public Node(AnyType d){ this.data=d; this.next=null; } public Node(){ this.data=null; this.next=null; }}public SingleLinkedStack(){top=null;theSize=0;}public boolean isEmpty(){return theSize==0;}public void push(AnyType x){Node<AnyType> newNode=new Node(x);newNode.next=top;top=newNode;theSize++;}public AnyType pop(){if(isEmpty())return null;AnyType a=top.data;top=top.next;theSize--;return a;}public static void main(String[] args) {SingleLinkedStack<String> sls=new SingleLinkedStack<String>();sls.push("aaa");sls.push("bbb");sls.push("ccc");sls.push("ddd");System.out.println(sls.pop());System.out.println(sls.pop());System.out.println(sls.pop());System.out.println(sls.pop());}}
- 栈的两种实现方法--数组实现与链式实现
- 栈的链式实现方法
- Algorithms: 栈(Stack) 链式与数组实现
- 队列的顺序实现(循环数组)与链式实现
- 栈的链式和数组存储实现
- 栈ADT链式实现及数组实现
- 栈的链式实现
- 链式栈的实现
- 栈的链式实现
- 链式栈的实现
- 链式栈的实现
- 链式栈的实现
- 链式栈的实现
- 链式栈的实现
- 栈的链式实现
- 栈的实现(链式)
- 链式栈的实现
- 链式栈的实现
- 基础概念:jdk与jre的区别
- CentOS编译安装NodeJS+Express
- 第七周上机实践项目——输入三个整数,输出其中的最大值
- Hash原理与HashMap
- Javascript跳转页面和打开新窗口等方法
- 栈的两种实现方法--数组实现与链式实现
- 2013.10.12北京360技术笔试(部分总结)
- [Cocos2D]如何创建Cocos2D-X的项目(版本号2.2)
- 第七周项目1-求并联电阻
- Cut Command Examples
- ResultSet 游标权限获取问题
- 解析泛泰手机rawdata/phoneinfo分区(以泛泰A850L为例)
- windows下用c++建立socket客户端
- STL list型容器的使用