class
Node {
int
data;
Node next;
Node prev;
public
Node(
int
data, Node next, Node prev) {
this
.data = data;
this
.next = next;
this
.prev = prev;
}
}
public
class
Main {
static
void
moveKthToFront(Node head,
int
K) {
if
(head ==
null
|| K <
1
|| K ==
1
) {
return
;
}
Node current = head;
Node prevKth =
null
;
for
(
int
i =
1
; i < K && current !=
null
; i++) {
prevKth = current;
current = current.next;
}
if
(current ==
null
) {
return
;
}
if
(prevKth !=
null
) {
prevKth.next = current.next;
}
if
(current.next !=
null
) {
current.next.prev = prevKth;
}
current.next = head;
head.prev = current;
current.prev =
null
;
head = current;
}
static
void
printList(Node head) {
while
(head !=
null
) {
System.out.print(head.data);
if
(head.next !=
null
) {
System.out.print(
" <-> "
);
}
head = head.next;
}
System.out.println(
" -> NULL"
);
}
public
static
void
main(String[] args) {
Node node1 =
new
Node(
2
,
null
,
null
);
Node node2 =
new
Node(
6
,
null
, node1);
Node node3 =
new
Node(
3
,
null
, node2);
Node node4 =
new
Node(
8
,
null
, node3);
Node node5 =
new
Node(
11
,
null
, node4);
Node node6 =
new
Node(
23
,
null
, node5);
Node node7 =
new
Node(
7
,
null
, node6);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
Node head = node1;
System.out.print(
"Original List: "
);
printList(head);
moveKthToFront(head,
4
);
System.out.print(
"Modified List: "
);
printList(head);
}
}