forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.java
More file actions
64 lines (53 loc) · 882 Bytes
/
LinkedStack.java
File metadata and controls
64 lines (53 loc) · 882 Bytes
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
63
64
package chap1;
import java.util.Iterator;
public class LinkedStack<Item> implements Iterable<Item>
{
private Node<Item> top;
private int N = 0;
public boolean isEmpty()
{
return (N == 0);
}
public int size()
{
return N;
}
public void push(Item item)
{
Node<Item> oldFirst = this.top;
top = new Node<Item>();
top.item = item;
top.next = oldFirst;
N++;
}
public Item pop()
{
Item item = top.item;
top = top.next;
N--;
return item;
}
public Item peek()
{
return top.item;
}
@Override
public Iterator<Item> iterator()
{
return new LinkedListIterator<Item>(top);
}
@Override
public String toString()
{
Node<Item> temp = top;
String result = null;
for(; temp != null; temp = temp.next)
{
if(temp == top)
result = temp.item.toString();
else
result += "->" + temp.item;
}
return result;
}
}