// Comment swaping k elements of a given linked list
public static LNode altReverse(LNode list, int k) {
if (list == null)
return list;
LNode oldHead = list;
int i = k;
while (list != null && i > 0) {
list = list.next;
i--;
}
LNode head = altReverse(list, k);
int j = k;
LNode curr = oldHead, prev = null;
while (curr != null && j > 0 && i == 0) {
LNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
j--;
}
if (i != 0)
return oldHead;
else {
oldHead.next = head;
return prev;
}
}
No comments:
Post a Comment