有关栈的笔记

栈是一种后进先出(Last In First Out,LIFO)的数据结构。栈可以理解为一种容器,只能在栈顶进行插入和删除操作,栈的底部是固定的而栈顶是动态变化的。由于其特殊的性质,在实际应用中,栈广泛运用在表达式求值、递归函数调用、系统内存管理等方面。

在Java中,可以使用数组或链表来实现栈。以下是一个用数组实现栈的示例代码:

public class ArrayStack {
    private int[] arr;
    private int top;
    private int maxSize;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
        this.top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public void push(int val) {
        if (isFull()) {
            System.out.println("Stack is full!");
            return;
        }
        arr[++top] = val;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        return arr[top--];
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        return arr[top];
    }

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop()); // output: 3
        System.out.println(stack.peek()); // output: 2
    }
}

以上示例代码实现了一个基于数组的栈,其中定义了栈的几个基本操作方法:isEmpty()isFull()push()pop()peek()。运行示例代码中的main方法,可以看到输出结果。

另外,以下是一个用链表实现栈的示例代码:

public class LinkedStack {
    class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    private Node top;

    public LinkedStack() {
        this.top = null;
    }

    public boolean isEmpty() {
        return top == null;
    }

    public void push(int val) {
        Node node = new Node(val);
        node.next = top;
        top = node;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        int val = top.val;
        top = top.next;
        return val;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        return top.val;
    }

    public static void main(String[] args) {
        LinkedStack stack = new LinkedStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop()); // output: 3
        System.out.println(stack.peek()); // output: 2
    }
}

以上示例代码实现了一个基于链表的栈,其中定义了栈的几个基本操作方法:isEmpty()push()pop()peek()。运行示例代码中的main方法,可以看到输出结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值