class
GFG {
GFG left, right;
int
data;
public
GFG(
int
val)
{
data = val;
left =
null
;
right =
null
;
}
}
class
Pagoda {
private
GFG root;
public
Pagoda()
{
root =
null
;
}
public
boolean
isEmpty()
{
return
root ==
null
;
}
public
void
clear()
{
root =
null
;
}
public
void
insert(
int
val)
{
GFG node =
new
GFG(val);
root = insert(node, root);
}
private
GFG insert(GFG node, GFG queue)
{
node.left = node;
node.right = node;
return
(merge(queue, node));
}
private
GFG merge(GFG root, GFG newnode)
{
GFG botroot, botnew, r, temp;
if
(root ==
null
)
return
newnode;
else
if
(newnode ==
null
)
return
root;
else
{
botroot = root.right;
root.right =
null
;
botnew = newnode.left;
newnode.left =
null
;
r =
null
;
while
(botroot !=
null
&& botnew !=
null
) {
if
(botroot.data < botnew.data) {
temp = botroot.right;
if
(r ==
null
)
botroot.right = botroot;
else
{
botroot.right = r.right;
r.right = botroot;
}
r = botroot;
botroot = temp;
}
else
{
temp = botnew.left;
if
(r ==
null
)
botnew.left = botnew;
else
{
botnew.left = r.left;
r.left = botnew;
}
r = botnew;
botnew = temp;
}
}
if
(botnew ==
null
) {
root.right = r.right;
r.right = botroot;
return
(root);
}
else
{
newnode.left = r.left;
r.left = botnew;
return
(newnode);
}
}
}
public
void
delete() { root = delete(root); }
private
GFG delete(GFG queue)
{
GFG l, r;
if
(queue ==
null
) {
System.out.println(
"Empty"
);
return
null
;
}
else
{
if
(queue.left == queue)
l =
null
;
else
{
l = queue.left;
while
(l.left != queue)
l = l.left;
l.left = queue.left;
}
if
(queue.right == queue)
r =
null
;
else
{
r = queue.right;
while
(r.right != queue)
r = r.right;
r.right = queue.right;
}
return
merge(l, r);
}
}
public
void
printRoot()
{
if
(root !=
null
)
System.out.println(root.data);
else
System.out.println(
"Empty"
);
}
}
public
class
GFG2 {
public
static
void
main(String[] args)
{
Pagoda p =
new
Pagoda();
p.insert(
10
);
System.out.print(
"Root Element : "
);
p.printRoot();
p.insert(
30
);
System.out.print(
"Root Element : "
);
p.printRoot();
p.insert(
20
);
System.out.print(
"Root Element : "
);
p.printRoot();
p.insert(
50
);
System.out.print(
"Root Element : "
);
p.printRoot();
p.insert(
40
);
System.out.print(
"Root Element : "
);
p.printRoot();
p.delete();
System.out.print(
"Root Element : "
);
p.printRoot();
p.delete();
System.out.print(
"Root Element : "
);
p.printRoot();
System.out.println(
"Empty status: "
+ p.isEmpty());
p.clear();
System.out.println(
"Empty status: "
+ p.isEmpty());
}
}