-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMyset.java
123 lines (114 loc) · 1.9 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
import java.util.*;
public class Myset
{
Node head;
static class Node
{
Object obj;
Node next, prev;
Node(Object o)
{
obj = o;
next = prev = null;
}
}
public boolean IsEmpty()
{
return (head==null);
}
public boolean IsMember(Object o)
{
Node temp = head;
while(temp != null)
{
if(temp.obj.equals(o))
return true;
temp = temp.next;
}
return false;
}
public void Insert(Object o)
{
if(IsMember(o)) throw new RuntimeException("Error - Object is already in the set");
Node tmp = new Node(o);
if(head==null)
{
head = tmp;
return;
}
Node n = head;
while(n.next != null)
n = n.next;
tmp.prev = n;
n.next = tmp;
}
public void Delete(Object o)
{
Node temp = head;
while(temp != null)
{
if(temp.obj.equals(o))
{
Node t = temp.next;
if(temp.prev != null) temp.prev.next = t;
else head = t;
if(t != null) t.prev = temp.prev;
return;
}
temp = temp.next;
}
throw new RuntimeException("Error - Given object is not present in set");
}
public Myset Union(Myset a)
{
Myset union = new Myset();
Node temp = head;
while(temp != null)
{
union.Insert(temp.obj);
temp = temp.next;
}
temp = a.head;
while(temp != null)
{
try { union.Insert(temp.obj); }
catch(RuntimeException ex) {}
temp = temp.next;
}
return union;
}
public Myset Intersection(Myset a)
{
Myset intersection = new Myset();
Node temp = head;
while(temp != null)
{
if(a.IsMember(temp.obj)) intersection.Insert(temp.obj);
temp = temp.next;
}
return intersection;
}
public int size()
{
Node tmp = head;
int count = 0;
while(tmp != null)
{
count++;
tmp = tmp.next;
}
return count;
}
public Object[] getItems()
{
int n = this.size();
Object[] objs = new Object[n];
Node tmp = head;
for(int i=0; i<n; i++)
{
objs[i] = tmp.obj;
tmp = tmp.next;
}
return objs;
}
}