数据结构-栈的实现及其操作【java】

数据结构-栈的实现及其操作【java】

静态栈的实现

package 数据结构.;

//以数组定义栈体——静态栈的实现
class Strack {
    //该栈最大空间为100
    int[] strack = new int[100];
    //top为最顶端层数加1,top从零开始
    int top;

    Strack() {
        //定义一个索引变量,表示栈顶指针
        int top = 0;
    }

    //显示栈的元素
    public void show() {
        for (int i = 0; i < top; i++) {
            System.out.print(strack[i]);
            System.out.print(' ');
        }
        System.out.println();
        return;
    }

    //进栈操作
    public void append(int i) {
        strack[top] = i;
        top += 1;
        return;
    }

    //退栈操作
    public int pop() {
        int x = strack[top-1];
        strack[top] = 0;
        top -= 1;
        return x;
    }
}

public class 栈的实现 {
    public static void main(String[] args) {
        Strack k = new Strack();
        k.append(10);
        k.append(20);
        k.append(30);
        k.show();
        int y = k.pop();
        System.out.println("退出的元素为:"+y);
        k.show();
    }
}

动态栈的实现

package 数据结构.;


//用双链表构造的栈体——动态栈

/*构造链表*/
//先构造链表节点
class link {
    int i;
    link next;

    link(int i) {
        this.i = i;
        this.next = null;
    }

    @Override
    public String toString() {
        return i+" ";
    }
}

//构造栈
class Strack_D {
    //构造栈顶指针——该指针一直指向顶层
    link top;

    Strack_D() {
        top = null;
    }

    //进栈操作
    void append(int x) {
        //new新节点
        link N = new link(x);
        //将N压入栈顶:N的next指向上一个节点,更新top——top指向N,动态替换的过程
        N.next = top;
        top = N;
    }

    //退栈操作
    int pop() {
        //将栈顶元素删除——top指向下一个节点,并返回栈顶元素值
        int x = top.i;
        top = top.next;
        return x;
    }

    //显示操作
    void show() {
        if (top==null){
            System.out.println("栈为空栈");
            return;
        }
        link team = top;
        //遍历输出节点,知道next==null
        while (true) {
            if (team == null) {
                break;
            }
            System.out.print(team);
            team = team.next;
        }
        System.out.println();
    }
}

public class 栈的实现_动态栈 {
    public static void main(String[] args) {
        Strack_D j = new Strack_D();
        j.append(10);
        j.append(20);
        j.append(30);
        j.show();
        int y = j.pop();
        System.out.println("退出的元素为:" + y);
        int x = j.pop();
        System.out.println("退出的元素为:" + x);
        System.out.println("剩余元素:");
        j.show();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值