学习笔记23 stack和queue

文章介绍了栈(Stack)数据结构的概念,使用Java内置的Stack类以及自定义的ArrayStack和LinkedList实现栈的方法,包括push、pop、empty等操作。同时,文章也提及了队列(Queue)的基本概念和操作方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、stack概念

stack是一种按先进后出方法存放和取出数据的数据结构

java提供了一个stack类,其中有以下几种方法:

看个例子:

import java.util.*;

/**
 * This program demonstrates the java.util.Stack class.
 */

public class StackDemo1 {
    public static void main(String[] args) {
        // Create a stack of strings and add some names
        Stack<String> stack = new Stack<>();
        String[] names = {"Al", "Bob", "Carol"};
        System.out.println("Pushing onto the stack the names:");
        System.out.println("Al Bob Carol");
        for (String s : names)
            stack.push(s);

        // Now pop and print everything on the stack
        String message = "Popping and printing all stack values:";
        System.out.println(message);
        while (!stack.empty())
            System.out.print(stack.pop() + " ");
    }
}
Pushing onto the stack the names:
Al Bob Carol
Popping and printing all stack values:
Carol Bob Al

 stack类不接受primitive data type,所以如果要存int,要转化为integer。

当然,如果你把primitive data type存入stack,java会自动box。

二、用array自己实现stack

public class ArrayStack {
    private int[] s; // Holds stack elements
    private int top; // Stack top pointer

    /**
     * Constructor.
     * @param capacity The capacity of the stack.
     */
    public ArrayStack(int capacity) {
        s = new int[capacity];
        top = 0;
    }

    /**
     * The empty method checks for an empty stack.
     * @return true if stack is empty.
     */
    public boolean empty() {
        return top == 0;
    }

    /**
     * The push method pushes a value onto the stack.
     * @param x The value to push onto the stack.
     * @exception StackOverflowException When the stack is full.
     */
    public void push(int x) {
        if (top == s.length)
            throw new StackOverflowException();
        else {
            s[top] = x;
            top++;
        }
    }

    /**
     * The pop method pops a value off the stack.
     * @return The value popped.
     * @exception EmptyStackException When the stack is empty.
     */
    public int pop() {
        if (empty())
            throw new EmptyStackException();
        else {
            top--;
            return s[top];
        }
    }

    /**
     * The peek method returns the value at the top of the stack.
     * @return value at top of the stack.
     * @exception EmptyStackException When the stack is empty.
     */
    int peek() {
        if (empty())
            throw new EmptyStackException();
        else {
            return s[top-1];
        }
    }
}

注意,我们需要自己实现两个异常类EmptyStackException StackOverFlowException

三、用linkedlist实现的stack

class LinkedStack {
    /**
     * The Node class is used to implement the linked list.
     */
    private class Node {
        String value;
        Node next;
        Node(String val, Node n) {
            value = val;
            next = n;
        }
    }

    private Node top = null; // Top of the stack

    /**
     * The empty method checks for an empty stack.
     * @return true if stack is empty, false otherwise.
     */
    public boolean empty() {
        return top == null;
    }

    /**
     * The push method adds a new item to the stack.
     * @param s The item to be pushed onto the stack.
     */
    public void push(String s) {
        top = new Node(s, top);
    }

    /**
     * The Pop method removes the value at the top of the stack.
     * @return The value at the top of the stack.
     * @exception EmptyStackException When the stack is empty.
     */
    public String pop() {
        if (empty())
            throw new EmptyStackException();
        else {
            String retValue = top.value;
            top = top.next;
            return retValue;
        }
    }

    /**
     * The peek method returns the top value on the stack.
     * @return The value at the top of the stack.
     * @exception EmptyStackException When the stack is empty.
     */
    public String peek() {
        if (empty())
            throw new EmptyStackException();
        else
            return top.value;
    }

    /**
     * The toString method computes a string representation of the contents of the stack.
     * @return The string representation of the stack contents.
     */
    public String toString() {
        StringBuilder sBuilder = new StringBuilder();
        Node p = top;
        while (p != null) {
            sBuilder.append(p.value);
            p = p.next;
            if (p != null)
                sBuilder.append("\n");
        }
        return sBuilder.toString();
    }
}

四、queue概念

queue是一种按先进先出方法存放和取出数据的数据结构

它应该包括如下方法:

enqueue(x): add a new item x to the rear of the queue
dequeue( ): remove and return the item at the front of the queue
empty( ): check if the queue is empty
peek( ): return, but do not remove, the item at the front of the queue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值