算法4学习-1.3.3.8 下压(LIFO)栈(链表实现)

上一篇的链表实现

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.Iterator;

/**
* 下压(LIFO)栈(链表实现)
*
* Created by tuzhis on 2016年1月14日.
*/
public class ReSizingArrayStack<Item> implements Iterable<Item> {

private Node first; // 栈顶(最近添加的元素)
private int N; // 元素数量

private class Node {
Item item;
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 ListIterator();
}

private class ListIterator implements Iterator<Item> {
private Node current = first;

@Override
public boolean hasNext() {
return current != null;
}

@Override
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}

}