java数据结构

本文介绍了如何使用链表实现一个栈的数据结构,包括代码实现、测试及操作结果展示。

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

实现基于链表的栈

代码实现:

import java.util.NoSuchElementException;

public class MyStack<E> {

    private Node<E> head;//头结点
    private Node<E> top;//栈顶
    private int size;//栈中元素个数

    public MyStack() {
        head = new Node<E>();
        head.next = null;
        top = null;//栈顶初始化为null
        size = 0;
    }

    /**
     * 把item压入栈中
     *
     * @param item
     */
    public void push(E item) {
        /********** Begin *********/
        if (top == null){
            top = new Node<>();
        }
        Node temp = head;
        while (temp.next != null){
            temp = temp.next;
        }
        Node newNode = new Node();
        newNode.item = item;
        temp.next = newNode;
        top = newNode;
        size++;
        /********** End *********/
    }

    /**
     * 返回它栈顶元素并删除
     */
    public E pop() {
        if (isEmpty())
            throw new NoSuchElementException("栈为空!");

        /********** Begin *********/
        Node temp = head.next;
        while (temp.next != null){
            if (temp.next.next == null){
                break;
            }
            temp = temp.next;
        }
        Node topNode = top;
        temp.next = null;
        top = temp;
        size--;
        return (E) topNode.item;
        /********** End *********/
    }

    /**
     * 返回栈中元素个数
     *
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 判断一个栈是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return (null == head);
    }

    //链表结点内部类
    private static class Node<E> {
        private E item;
        private Node<E> next;
    }
}

代码测试:

public class MyStackTest {
    public static void main(String[] args) {
        MyStack<String> s = new MyStack<>();
        Scanner in = new Scanner(System.in);
        while (in.hasNext()){
            String str = in.next();
            if (!str.equals("-")) {
                s.push(str);
            } else {
                System.out.print(s.pop() + " ");
            }
        }
    }
}

结果展示:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值