Skip to main content
 首页 » 编程设计

java算法之自定义线性结构---栈

2022年07月18日42jirigala
/** 
 * @desc:  栈结构-单链表实现 
 * @author: 毛会懂 
 * @create: 2020-12-29 18:03:00 
 **/ 
public class MyStack<T> implements Iterable<T>{ 
    private Node head; //头节点,指向栈顶,默认指向空 
    private Integer count;//栈的大小 
 
    public MyStack(){ 
        head = new Node(null,null); 
        count = 0; 
    } 
 
    //进栈 
    public void push(T t){ 
        Node node = new Node(t,head.next); 
        head.next = node; 
        count++; 
    } 
 
    //出栈 
    public T pop(){ 
        if(head.next != null){ 
            Node node = head.next; 
            head.next = node.next; 
            count--; 
            return node.t; 
        } 
        return null; 
    } 
 
    //是否空栈 
    public Boolean isEmpty(){ 
        return count == 0; 
    } 
 
    //栈的大小 
    public Integer size(){ 
        return count; 
    } 
 
    @Override 
    public Iterator<T> iterator() { 
        return new MyIterator(head); 
    } 
 
    private class MyIterator implements Iterator{ 
        private Node node; 
 
        public MyIterator(Node head) { 
            this.node = head; 
        } 
 
        @Override 
        public boolean hasNext() { 
            return node.next != null; 
        } 
 
        @Override 
        public T next() { 
            node = node.next; 
            return node.t; 
        } 
    } 
 
    private class Node{ 
        private T t; 
        private Node next; 
 
        public Node(T t, Node next) { 
            this.t = t; 
            this.next = next; 
        } 
    } 
}

测试:

public static void main(String[] args) {
MyStack<Integer> myStack = new MyStack<>();
myStack.push(10);
myStack.push(20);
System.out.println("第一次出栈:"+myStack.pop());
System.out.println("栈的大小:" + myStack.size());
System.out.println("栈是否为空:" + myStack.isEmpty());
System.out.println("第一次遍历栈");
for (Integer i : myStack){
System.out.println(i);
}
System.out.println("第二次遍历栈");
myStack.forEach(System.out::println);
System.out.println("结束");
System.out.println("第二次出栈:" + myStack.pop());
System.out.println("第三次出栈:" + myStack.pop());
}

本文参考链接:https://www.cnblogs.com/maohuidong/p/14216133.html