-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMyset.java
146 lines (110 loc) · 2.29 KB
/
Myset.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import java.util.*;
public class Myset{
node head;
class node{
Object data;
node next;
}
public Boolean IsEmpty() {
if(head == null) return true;
return false;
}
public int numberOfObjects(){
node temp = new node();
temp = head;
int count = 0;
while(temp != null){
count++;
temp = temp.next;
}
return count;
}
//REQD TO RETURN ALL OBJECTS (IN ANY ORDER)
public Object nthObject(int n){
if(n >= numberOfObjects())
return null;
node temp = head;
for (int i = 0; i < n; i++) {
temp = temp.next;
}
return temp.data;
}
public Boolean IsMember(Object o) {
node temp = head;
while( temp != null ) {
if(temp.data.equals(o)) return true;
temp = temp.next;
}
return false;
}
public void Insert(Object o) {
if(IsMember(o)) return;
node newnode = new node();
newnode.data = o;
newnode.next = null;
if(head == null){
head = newnode;
return;
}
node temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = newnode;
return;
}
public void Delete(Object o) {
if( IsEmpty() == true)
throw new NoSuchElementException();
node temp = head;
if(head.data.equals(o))
head = head.next;
while( temp != null ) {
if(temp.data.equals(o)) return;
if(temp.next.data.equals(o)) {
temp.next = temp.next.next;
return;
}
temp = temp.next;
}
throw new NoSuchElementException();
}
public Myset Union(Myset a) {
//if( IsEmpty() && a.IsEmpty() ) return null;//both empty
if ( a.IsEmpty() ) return this;//a empty
if ( this.IsEmpty() ) return a;//our set empty
Myset res = this;
node temp2 = new node();
temp2 = a.head;
node temp = new node();
temp = res.head;
while (temp.next != null) {
temp = temp.next;
}
while (temp2 != null) {
if(!(res.IsMember(temp2.data))) {
temp.next = temp2;
temp = temp.next;
}
temp2 = temp2.next;
}
node p = new node();
p = res.head;
while (p != null) {
//System.out.println(p.data);
p = p.next;
}
return res;
}
public Myset Intersection(Myset a) {
Myset res = new Myset();
node temp1 = new node();
temp1 = head;
while(temp1 != null) {
if (a.IsMember(temp1.data)) {
res.Insert(temp1.data);
}
temp1 = temp1.next;
}
return res;
}
}