栈的api设计
栈类
package stack;
import java.util.Iterator;
public class StackByLink<T> implements Iterable<T> {
private int N;
private Node head;
//节点成员内部类
private class Node {
public T item;
public Node next;
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
public StackByLink() {
this.N = 0;
this.head = new Node(null,null);
}
public boolean isEmpty() {
return N == 0;
}//判断栈是否为空,是返回true,否返回false
public int size() {
return N;
}//获取栈中元素的个数
public T pop() {
Node oldfirst = head.next;
if (oldfirst == null) {
return null;
}
head.next = oldfirst.next;
N--;
return oldfirst.item;
}//弹出栈顶元素
public void push(T t) {
Node oldfirst = head.next;
Node newNode = new Node(t, null);
head.next = newNode;
newNode.next = oldfirst;
N++;
}//向栈中压入元素t
@Override
public Iterator<T> iterator() {
return new StackIterator();
}
private class StackIterator implements Iterator {
private Node n;
public StackIterator() {
this.n = head;
}
@Override
public boolean hasNext() {
return n.next != null;
}
@Override
public Object next() {
n = n.next;
return n.item;
}
}
}
测试类
package stack;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
StackByLink<String> stackByLink = new StackByLink<>();
stackByLink.push("1");
stackByLink.push("2");
stackByLink.push("3");
stackByLink.push("4");
Iterator<String> iterator = stackByLink.iterator();
while (iterator.hasNext()) {
System.out.println("弹出元素" + iterator.next());
}
System.out.println(stackByLink.pop());
System.out.println(stackByLink.size());
}
}