Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

用java实现堆栈

  1. User

    用java实现堆栈

  2. Assistant

    下面是一个用Java实现堆栈的示例代码:

    import java.util.ArrayList;
    
    public class Stack {
        private ArrayList<Integer> stack;
    
        public Stack() {
            stack = new ArrayList<>();
        }
    
        public void push(int value) {
            stack.add(value);
        }
    
        public int pop() {
            if (isEmpty()) {
                throw new RuntimeException("Stack is empty");
            }
            return stack.remove(stack.size() - 1);
        }
    
        public int peek() {
            if (isEmpty()) {
                throw new RuntimeException("Stack is empty");
            }
            return stack.get(stack.size() - 1);
        }
    
        public boolean isEmpty() {
            return stack.isEmpty();
        }
    
        public int size() {
            return stack.size();
        }
    
        public static void main(String[] args) {
            Stack stack = new Stack();
    
            stack.push(1);
            stack.push(2);
            stack.push(3);
    
            System.out.println("Size of stack: " + stack.size());
            System.out.println("Top element: " + stack.peek());
    
            while (!stack.isEmpty()) {
                System.out.println("Popped element: " + stack.pop());
            }
    
            System.out.println("Size of stack: " + stack.size());
        }
    }
    

    这里使用了ArrayList作为堆栈的底层数据结构,push方法将元素添加到列表的末尾,pop方法从列表的末尾移除并返回元素,peek方法返回列表的末尾元素但不移除,isEmpty方法检查堆栈是否为空,size方法返回堆栈的大小。

    在main方法中,我们对堆栈进行了一些操作:将元素1、2和3依次入栈,然后输出堆栈的大小和顶部元素。接着我们通过循环将堆栈中的元素逐个弹出并输出,最后再次输出堆栈的大小,可以看到堆栈已经为空。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.