关闭

Java实现Stack类

发表于:2015-9-10 09:47

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:_无忧无虑    来源:51Testing软件测试网采编

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Stack<Item> implements Iterable<Item> {
private int N;
private Node<Item> first;
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
public Stack() {
first = null;
N = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
N ++;
}
public Item pop() {
if(isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item;
first = first.next;
N --;
return item;
}
public Item peek() {
if(isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}
public String toString() {
StringBuilder s = new StringBuilder();
for(Item item : this)
s.append(item + " ");
return s.toString();
}
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
}
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if(!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args) {
Stack<String> s = new Stack<String>();
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String item = in.next();
if(!item.equals("-")) s.push(item);
else if(!s.isEmpty()) System.out.println(s.pop() + " ");
System.out.println("(" + s.size() + " left on stack)");
}
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号