import
java.util.ArrayList;
import
java.util.HashSet;
import
java.util.List;
import
java.util.Objects;
import
java.util.Set;
import
java.util.Collections;
class
Node {
int
data;
Node next;
public
Node(
int
data) {
this
.data = data;
this
.next =
null
;
}
public
Node xor(Node a, Node b) {
return
a !=
null
? (b !=
null
? (Objects.hash(a, b) ==
0
?
null
:
this
) : a) : b;
}
}
public
class
XORLinkedList {
private
Node head;
public
XORLinkedList() {
this
.head =
null
;
}
public
void
insert(
int
newData) {
Node newNode =
new
Node(newData);
if
(head !=
null
) {
newNode.next = head;
head = newNode;
}
else
{
head = newNode;
}
}
public
List<Pair> findPairsWithSum(
int
x) {
if
(head ==
null
) {
System.out.println(
"No elements in the list."
);
return
Collections.emptyList();
}
Set<Integer> visitedValues =
new
HashSet<>();
Node current = head;
List<Pair> pairs =
new
ArrayList<>();
while
(current !=
null
) {
int
neededValue = x - current.data;
if
(visitedValues.contains(neededValue)) {
pairs.add(
new
Pair(Math.min(neededValue, current.data),
Math.max(neededValue, current.data)));
}
visitedValues.add(current.data);
current = current.next;
}
return
pairs;
}
public
static
void
main(String[] args) {
XORLinkedList xorList =
new
XORLinkedList();
int
x =
17
;
xorList.insert(
11
);
xorList.insert(
10
);
xorList.insert(
9
);
xorList.insert(
8
);
xorList.insert(
7
);
xorList.insert(
6
);
xorList.insert(
3
);
List<Pair> pairs = xorList.findPairsWithSum(x);
Collections.sort(pairs);
if
(pairs.isEmpty()) {
System.out.println(
"No pair found"
);
}
else
{
for
(Pair pair : pairs) {
System.out.println(
"("
+ pair.first +
","
+ pair.second +
")"
);
}
}
}
static
class
Pair
implements
Comparable<Pair> {
int
first;
int
second;
public
Pair(
int
first,
int
second) {
this
.first = first;
this
.second = second;
}
@Override
public
int
compareTo(Pair other) {
if
(
this
.first == other.first) {
return
Integer.compare(
this
.second, other.second);
}
return
Integer.compare(
this
.first, other.first);
}
}
}