Skip to content

Commit f7fac56

Browse files
committed
Set
1 parent 0139178 commit f7fac56

File tree

4 files changed

+81
-2
lines changed

4 files changed

+81
-2
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.example.datastructure;
2+
3+
/**
4+
* 基于二分搜索树的set
5+
*/
6+
public class BSTSet<E extends Comparable<E>> implements Set<E>{
7+
private BinarySearchTree<E> mBst;
8+
9+
public BSTSet() {
10+
this.mBst = new BinarySearchTree<>();
11+
}
12+
13+
@Override
14+
public int getSize() {
15+
return mBst.getSize();
16+
}
17+
18+
@Override
19+
public boolean isEmpty() {
20+
return mBst.isEmpty();
21+
}
22+
23+
@Override
24+
public void add(E e) {
25+
mBst.add(e);
26+
}
27+
28+
@Override
29+
public boolean contains(E e) {
30+
return mBst.contains(e);
31+
}
32+
}

app/src/main/java/com/example/datastructure/BinarySearchTree.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public void inOrder() {
8989
inOrder(root);
9090
}
9191

92-
private void inOrder(Node node){
92+
private void inOrder(Node node) {
9393
inOrder(node.left);
9494
Log.d("访问节点", node.e.toString());
9595
inOrder(node.right);
@@ -101,7 +101,7 @@ public void postOrder() {
101101
postOrder(root);
102102
}
103103

104-
private void postOrder(Node node){
104+
private void postOrder(Node node) {
105105
postOrder(node.left);
106106
postOrder(node.right);
107107
Log.d("访问节点", node.e.toString());
@@ -111,6 +111,10 @@ public boolean isEmpty() {
111111
return size == 0;
112112
}
113113

114+
public int getSize() {
115+
return size;
116+
}
117+
114118
private class Node {
115119
public E e;
116120
public Node left, right;
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.example.datastructure;
2+
3+
/**
4+
* 基于链表的Set
5+
*/
6+
public class LinkedListSet<E> implements Set<E>{
7+
private LinkedList<E> linkedList;
8+
9+
public LinkedListSet() {
10+
this.linkedList = new LinkedList<>();
11+
}
12+
13+
@Override
14+
public int getSize() {
15+
return linkedList.getSize();
16+
}
17+
18+
@Override
19+
public boolean isEmpty() {
20+
return linkedList.isEmpty();
21+
}
22+
23+
//链表本身不去重
24+
@Override
25+
public void add(E e) {
26+
if (!linkedList.contains(e)){
27+
linkedList.addFirst(e);
28+
}
29+
}
30+
31+
@Override
32+
public boolean contains(E e) {
33+
return linkedList.contains(e);
34+
}
35+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.example.datastructure;
2+
3+
public interface Set<E> {
4+
int getSize();
5+
boolean isEmpty();
6+
void add(E e);
7+
boolean contains(E e);
8+
}

0 commit comments

Comments
 (0)