-
Notifications
You must be signed in to change notification settings - Fork 113
/
Stack.java
74 lines (65 loc) · 1.7 KB
/
Stack.java
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
65
66
67
68
69
70
71
72
73
74
import java.util.Iterator;
public class Stack<Item> implements Iterable<Item>{
private Node first;
private int N;
private class Node{
Item item;
Node next;
}
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;
N--;
first = first.next;
return item;
}
public Item peek(){
return first.item;
}
public boolean isEmpty(){
return first == null;
}
public int size(){
return N;
}
public Iterator<Item> iterator(){
return new ListIterator();
}
public class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext(){
return current != null;
}
public Item next(){
Item item = current.item;
current = current.next;
return item;
}
public void remove(){
}
}
public static void main(String[] args){
Stack<String> s = new Stack<String>();
while(!StdIn.isEmpty()){
String item = StdIn.readString();
if(!item.equals("-"))
s.push(item);
else{
if(!s.isEmpty()) System.out.print(s.pop() + " ");
}
}
System.out.println();
System.out.println("Size left on the stack is " + s.size());
}
}
/*
C:\Users\ngunti\algs4\FundamentalsOfProgramming\BagsQueuesStacks>java-algs4 Stack <tobe.txt
to be not that or be
Size left on the stack is 2
*/