数据结构之通过链表实现栈

栈的api设计
在这里插入图片描述

栈类

package stack;

import java.util.Iterator;

public class StackByLink<T> implements Iterable<T> {
    private int N;
    private Node head;

    //节点成员内部类
    private class Node {
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public StackByLink() {
        this.N = 0;
        this.head = new Node(null,null);
    }

    public boolean isEmpty() {
        return N == 0;
    }//判断栈是否为空,是返回true,否返回false

    public int size() {
        return N;
    }//获取栈中元素的个数

    public T pop() {
        Node oldfirst = head.next;
        if (oldfirst == null) {
            return null;
        }
        head.next = oldfirst.next;
        N--;
        return oldfirst.item;

    }//弹出栈顶元素

    public void push(T t) {
        Node oldfirst = head.next;
        Node newNode = new Node(t, null);
        head.next = newNode;
        newNode.next = oldfirst;
        N++;
    }//向栈中压入元素t

    @Override
    public Iterator<T> iterator() {
        return new StackIterator();
    }

    private class StackIterator implements Iterator {
        private Node n;

        public StackIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }
}

测试类

package stack;

import java.util.Iterator;

public class Test {
    public static void main(String[] args) {
        StackByLink<String> stackByLink = new StackByLink<>();
        stackByLink.push("1");
        stackByLink.push("2");
        stackByLink.push("3");
        stackByLink.push("4");

        Iterator<String> iterator = stackByLink.iterator();
        while (iterator.hasNext()) {
            System.out.println("弹出元素" + iterator.next());
        }
        System.out.println(stackByLink.pop());
        System.out.println(stackByLink.size());

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值