Java实现Stack类
作者:网络转载 发布时间:[ 2015/9/10 15:19:49 ] 推荐标签:测试开发技术 开发语言
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/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11