用链表实现栈demo
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用链表实现栈demo相关的知识,希望对你有一定的参考价值。
package cn.aust.zyw.demo; import java.util.Iterator; /** * Created by zyw on 2016/2/20. */ public class Stack<Item> implements Iterable<Item>{ private Node first; private int N; private class Node{ private Item item; private Node next; } public boolean isEmpty(){return first==null;} public int size(){return N;} public void push(Item item){ Node oldfirst=first; first=new Node(); first.item=item; first.next=oldfirst; N++; } public Item pop(){ Item item=first.item; first=first.next; N--; return item; } @Override public Iterator<Item> iterator() { return new Iterator<Item>() { private int i=N; @Override public boolean hasNext() { if(i-->0) return true; return false; } @Override public Item next() { Item item=first.item; first=first.next; return item; } }; } public static void main(String args[]){ Stack<Double> mystack=new Stack<>(); mystack.push(1.5); mystack.push(1.3); mystack.push(1.0); Iterator iter=mystack.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } } }
以上是关于用链表实现栈demo的主要内容,如果未能解决你的问题,请参考以下文章