新手,正在学Java Collection,瞎写点东西-一个基于链表的stack及其遍历

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 11:42:36

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

 

import java.util.Iterator;

public class LinkedStack<U> {

    private class Node<T> {
        T data; 
        Node<T> next; 
        
        Node() {
            data = null; 
            next = null; 
        }
        
        Node(T data, Node<T> next) {
            this.data = data; 
            this.next = next; 
        }
       
        boolean end() {
            return data == null && next == null; 
        }
    }
    
    private Node<U> top = new Node<U>(); 
    
    public U pop() {
        U result = top.data; 
        if (!top.end()) 
            top = top.next; 
        return result; 
    }
    
    public void push(U data) { 
        top = new Node<U>(data, top); 
    }
    
    public Iterator<U> iterator() {
        return new Iterator<U>() {
            public boolean hasNext() {
                return !top.end(); 
            }

            public U next() {
                return pop(); 
            }

            public void remove() {
                throw new UnsupportedOperationException(); 
            } 
        }; 
    }
    
    public static void main(String[] args) {
        LinkedStack<Integer> test = new LinkedStack<Integer>(); 
        for (int i=0; i<10; i++) 
            test.push(i); 
        
        Iterator<Integer> it = test.iterator(); 
        while (it.hasNext()) 
            System.out.println(it.next()); 
    }
    
}
 

没事,写着玩呢!呵呵!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!