用链表实现栈数据结构(JAVA版)

本文介绍了一种使用链表实现栈的数据结构方法。通过在链表头部插入元素来完成push操作,删除链表头部节点实现pop操作。文章详细展示了链表节点的定义及基于链表的栈的具体实现。

链表实现栈

链表也可以实现栈,通过在表头插入元素的方式实现push操作,删除链表的表头结点的方式实现pop操作
在这里插入图片描述

链表结构

/**
 * 单向链表
 */
public class ListNode {

    private int data;

    private ListNode next;

    public ListNode(int data) {
        this.data = data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public int getData() {
        return this.data;
    }

    public void setNext(ListNode next) {
        this.next = next;
    }

    public ListNode getNext() {
        return this.next;
    }
    
}

链表的栈实现

/**
 * 基于链表的栈的实现
 */
public class LinkedListStack {

    private ListNode head = null;

    public LinkedListStack() {
        head = new ListNode(0);
    }

    public void Push(int data) {
        if (head == null) {
            head = new ListNode(data);
        } else if (head.getData() == 0) {
            head.setData(data);
        } else {
            ListNode node = new ListNode(data);
            node.setNext(head);
            head = node;
        }
    }

    public int pop() {
        if (head == null) {
            throw new EmptyStackException();
        } else {
            int data = head.getData();
            head = head.getNext();
            return data;
        }
    }

    public int top() {
        if (head == null) {
            return 0;
        } else {
            return head.getData();
        }
    }

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

    public void deleteStack() {
        head = null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值