import
java.util.ArrayList;
import
java.util.List;
class
Node {
int
data;
Node next;
public
Node(
int
val) {
data = val;
next =
null
;
}
}
public
class
LinkedListPermutations {
private
static
void
swap(
int
[] arr,
int
x,
int
y) {
int
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
private
static
void
swapNodes(Node a, Node b) {
int
temp = a.data;
a.data = b.data;
b.data = temp;
}
private
static
void
printLinkedList(Node head) {
while
(head !=
null
) {
System.out.print(head.data);
if
(head.next !=
null
) {
System.out.print(
" -> "
);
}
head = head.next;
}
System.out.println(
" -> null"
);
}
private
static
void
permutations(List<Node> res, Node head, Node current) {
if
(current ==
null
) {
Node newHead =
new
Node(-
1
);
Node tail = newHead;
Node temp = head;
while
(temp !=
null
) {
tail.next =
new
Node(temp.data);
tail = tail.next;
temp = temp.next;
}
res.add(newHead.next);
}
else
{
Node temp = current;
while
(temp !=
null
) {
swapNodes(current, temp);
permutations(res, head, current.next);
swapNodes(current, temp);
temp = temp.next;
}
}
}
private
static
List<Node> permuteLinkedList(Node head) {
List<Node> res =
new
ArrayList<>();
permutations(res, head, head);
return
res;
}
public
static
void
main(String[] args) {
Node head =
new
Node(
1
);
head.next =
new
Node(
2
);
head.next.next =
new
Node(
3
);
List<Node> res = permuteLinkedList(head);
for
(Node linkedList : res) {
printLinkedList(linkedList);
}
}
}