栈的存储结构

来源:互联网 发布:淘宝怎么看卖家的评价 编辑:程序博客网 时间:2024/05/29 16:20

(1)栈的定义:限制在表的一端进行删除和插入的线性表,通常能够插入和删除的一端为栈顶(top);
(2)顺序栈:顺序栈的实现,从本质上来讲就是顺序线性表的实现,唯一重要的是应该用数组的那一端表示栈顶。主要操作是出栈和入栈,也就是修改栈顶指针;入栈
出栈

java代码实现:class SqStack{    private int[] stack;       private int top;    public SqStack(){        this(10);    //在构造方法内部使用this关键词调用其他方法时,调用方法只能出现在内部的第一行可执行代码。    }    public SqStack(int size){        this.stack=new int[size];        this.top=0;     }    public void push(int val){   //入栈        if(full())            resize();        this.stack[++top]=val;    }    public void pop(){    //出栈        if(empty())            return;        top--;    }    public int top(){   //取栈顶元素;        return this.stack[top--];    }    public boolean empty(){        return this.top==0;     }    public boolean full(){        return this.top==this.stack.length;     }    public void resize(){        stack=Arrays.copyOf(stack, stack.length*2); //扩容    }

(2)链式栈:堆栈的链式存储结构,对链表的头部操作来实现出栈和入栈,链式栈的好处是不存在溢出;

java代码实现:class Node{   //定义一个结点     int value;    Node next;    public Node(){        this(0);    }    public Node(int value){   //对结点初始化        this.value=value;       }}class LinkStack{    Node bottom;    Node top;    public LinkStack(){        this.top=new Node(0);       }    public void push(int val){        Node n=new Node(val);  //先申请结点         n.next=top;   //新结点的next指向旧结点;        top=n;      }    public void pop(){        if(empty())            return;        top=top.next;       }    public int top(){        return top.value;       }    public boolean empty(){        return top==bottom;     }    //给类对象提供toString的方法    public String toString(){        StringBuilder builder=new StringBuilder();        Node n=top;        while(n!=bottom){            builder.append(n.value+ " ");            n=n.next;        }        return builder.toString();      }}main函数实现测试:public class TestLinkStack {    public static void main(String[] args) {        // TODO Auto-generated method stub        LinkStack s=new LinkStack ();        Random r=new Random();        for(int i=0;i<20;i++){            int n=r.nextInt(100);            s.push(n);        }        System.out.println(s.toString());    }}