<script>
class Node {
constructor() {
this
.data = 0;
this
.next =
null
;
}
}
function
newNode(data) {
var
temp =
new
Node();
temp.data = data;
temp.next =
null
;
return
temp;
}
function
printList(head) {
var
temp = head;
while
(temp !=
null
) {
document.write(temp.data +
" "
);
temp = temp.next;
}
document.write(
"<br>"
);
}
function
push(head_ref, new_data) {
var
new_Node =
new
Node();
new_Node.data = new_data;
new_Node.next = head_ref;
head_ref = new_Node;
return
head_ref;
}
function
getSize(head) {
var
curr = head;
var
count = 0;
while
(curr !=
null
) {
curr = curr.next;
count++;
}
return
count;
}
function
reverseSizeBy2Util(head, k, skipMiddle) {
if
(head ==
null
)
return
null
;
var
count = 0;
var
curr = head;
var
prev =
null
;
var
next =
null
;
while
(curr !=
null
&& count < k) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
if
(!skipMiddle) head.next =
reverseSizeBy2Util(next, k,
false
);
else
{
head.next = next;
if
(next !=
null
) next.next =
reverseSizeBy2Util(next.next, k,
true
);
}
return
prev;
}
function
reverseBySizeBy2(head) {
var
n = getSize(head);
if
(n % 2 == 0)
return
reverseSizeBy2Util(head, parseInt(n / 2),
false
);
else
return
reverseSizeBy2Util(head, parseInt(n / 2),
true
);
}
var
head =
null
;
head = push(head, 9);
head = push(head, 8);
head = push(head, 7);
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
document.write(
"Original List : "
);
printList(head);
document.write(
"Reversed List : "
);
var
reversedHead = reverseBySizeBy2(head);
printList(reversedHead);
</script>