简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test3;
import java.util.LinkedList;
import java.util.Queue;
public class SequentailSearchST<Key, Value> {
private Node first;
private int n;
private class Node {
Key key;
Value value;
Node next;
public Node(Key key, Value value, Node next) {
this.key = key;
this.value = value;
this.next = next;
}
}
public void delete(Key key) {
Node x = first;
Node last = null;
while (x != null) {
if (key.equals(x.key)) {
last.next = x.next;
n--;
} else {
last = x;
}
x=x.next;
}
}
public Iterable<Key> keys() {
Queue<Key> queue = new LinkedList<>();
for (Node x = first; x != null; x = x.next) {
queue.add(x.key);
}
return queue;
}
public Value get(Key key) {
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
return x.value;
}
}
return null;
}
public boolean contains(Key key) {
return get(key) != null;
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
public void put(Key key, Value value) {
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
x.value = value;
return;
}
}
first = new Node(key, value, first);
n++;
}
public static void main(String[] args) {
SequentailSearchST<String, Integer> st = new SequentailSearchST<>();
String test = "S E A R C H E X A M P L E";
String[] keys = test.split(" ");
for (int i = 0; i < keys.length; i++) {
st.put(keys[i], i);
}
System.out.println("size = " + st.size());
System.out.println("isEmpty = " + st.isEmpty());
System.out.println("contains = " + st.contains("S"));
st.delete("S");
System.out.println("contains = " + st.contains("S"));
for (String key : st.keys()) {
System.out.println(key + " " + st.get(key));
}
}
}
输出
size = 10
isEmpty = false
contains = true
contains = false
L 11
P 10
M 9
X 7
H 5
C 4
R 3
A 8
E 12
Happy learning !!