import
java.io.*;
import
java.util.Scanner;
class
Node {
int
element, sValue;
Node left, right;
public
Node(
int
element) {
this
(element,
null
,
null
); }
public
Node(
int
element, Node left, Node right)
{
this
.element = element;
this
.left = left;
this
.right = right;
this
.sValue =
0
;
}
}
class
LeftHeap {
private
Node head;
public
LeftHeap() { head =
null
; }
public
boolean
isEmpty()
{
return
head ==
null
;
}
public
void
clear()
{
head =
null
;
}
public
void
merge(LeftHeap rhs)
{
if
(
this
== rhs)
return
;
head = merge(head, rhs.head);
rhs.head =
null
;
}
public
Node merge(Node a, Node b)
{
if
(a ==
null
)
return
b;
if
(b ==
null
)
return
a;
if
(a.element > b.element) {
Node temp = a;
a = b;
b = temp;
}
a.right = merge(a.right, b);
if
(a.left ==
null
) {
a.left = a.right;
a.right =
null
;
}
else
{
if
(a.left.sValue < a.right.sValue) {
Node temp = a.left;
a.left = a.right;
a.right = temp;
}
a.sValue = a.right.sValue +
1
;
}
return
a;
}
public
void
insert(
int
a)
{
head = merge(
new
Node(a), head);
}
public
int
del()
{
if
(isEmpty())
return
-
1
;
int
min = head.element;
head = merge(head.left, head.right);
return
min;
}
public
void
order()
{
order(head);
System.out.println();
}
private
void
order(Node r)
{
if
(r !=
null
) {
order(r.left);
System.out.print(r.element +
" "
);
order(r.right);
}
}
}
class
GFG {
public
static
void
main(String[] args)
{
Scanner sc =
new
Scanner(System.in);
System.out.println(
"LEFTIST HEAP"
);
LeftHeap h =
new
LeftHeap();
char
ch;
do
{
System.out.println(
"Functions to do"
);
System.out.println(
"1. insert"
);
System.out.println(
"2. delete min"
);
System.out.println(
"3. check empty"
);
System.out.println(
"4. clear"
);
int
choice = sc.nextInt();
switch
(choice) {
case
1
:
System.out.println(
"Enter integer element to insert"
);
h.insert(sc.nextInt());
break
;
case
2
:
h.del();
break
;
case
3
:
System.out.println(
"Empty status = "
+ h.isEmpty());
break
;
case
4
:
h.clear();
break
;
default
:
System.out.println(
"Wrong entry"
);
break
;
}
System.out.print(
"\n Inorder Traversal: "
);
h.order();
System.out.println(
"\n If you wish to continue type Y or y"
);
ch = sc.next().charAt(
0
);
}
while
(ch ==
'Y'
|| ch ==
'y'
);
}
}