-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStackLL.java
More file actions
57 lines (49 loc) · 1.1 KB
/
Copy pathStackLL.java
File metadata and controls
57 lines (49 loc) · 1.1 KB
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
import java.util.Iterator;
import java.lang.Iterable;
public class StackLL<Item> implements Iterable<Item>
{
// get an iterator
public Iterator<Item> iterator() { return new ListIterator(); }
private class ListIterator implements Iterator<Item>
{
private Node current = first;
public boolean hasNext()
{
return current != null;
}
public void remove()
{
// not supported
}
public Item next()
{
Item item = current.item;
current = current.next;
return item;
}
}
private class Node
{
Item item;
Node next;
public Node(Item item)
{
this.item = item;
}
}
Node first;
public void push(Item item)
{
// O(1)
Node oldfirst = first;
first = new Node(item);
first.next = oldfirst;
}
public Item pop()
{
// O(1)
Item item = first.item;
first = first.next;
return item;
}
}