-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSequentialSearchST.java
112 lines (85 loc) · 2.24 KB
/
SequentialSearchST.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
public class SequentialSearchST<Key, Value> {
private Node first;
private int n = 0;
private class Node {
private Key key;
private Value val;
private Node next;
public Node(Key key, Value val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
}
public SequentialSearchST() {
}
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
x.val = val;
return;
}
}
Node newNode = new Node(key, val, first);
first = newNode;
n++;
}
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
for(Node x = first; x != null; x = x.next) {
if (x.key == key) {
return x.val;
}
}
return null;
}
public boolean contains(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
return get(key) != null;
}
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
first = delete(first, key);
}
private Node delete(Node x, Key key) {
if (x == null) return null;
if (key.equals(x.key)) {
n--;
return x.next;
}
x.next = delete(x.next, key);
return x;
}
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (Node x = first; x != null; x = x.next)
queue.enqueue(x.key);
return queue;
}
public static void main(String[] args) {
SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>();
st.put("A", 2);
st.put("S", 3);
st.put("T", 6);
st.put("W", 0);
st.put("A", 9);
for (String x:st.keys()) {
System.out.printf("Keys: %s - Values: %s\n", x, st.get(x));
}
System.out.println(st.get("A"));
System.out.println(st.n);
st.delete("A");
st.delete("B");
st.delete("T");
System.out.println(st.n);
System.out.println(st.get("A"));
for (String x:st.keys()) {
System.out.printf("Keys: %s - Values: %s\n", x, st.get(x));
}
}
}