This is a
sample program that when given the head of a linked list, reverses the nodes of
the list k at a time, and returns the modified list.
k is a positive
integer and is less than or equal to the length of the linked list. If the
number of nodes is not a multiple of k then left-out nodes, in the end, would
remain as it is.
Node reverseK(Node head, int k)
{
int n = 0;
for ( Node cur = head; cur !=
null; cur=cur.next) {n++};
Node cur = head;
Node prev =null;
Node root = null;
for (int i = 0; i < (n/k) + 1;
i++)
{
Node next = cur;
For (int j = 0; next != null && j <k-1; j++) { next=next.next;}
Node Temp = null;
If (next) {
temp = next.next;
Next.next = null;
}
If (temp != null) {
reverse(ref cur, ref next);
head =cur;
next.next = temp;
}
if (!root) {root = head};
while(cur != null && cur.next != null && cur.next !=
next){ cur = cur.next;};
if (!prev){
prev = cur;
cur = cur.next;
} else {
prev.next=head;
prev = head;
}
cur=temp;
next = temp;
}
return root;
}
void reverse(ref
node start, ref node end) {
if (start == null) return;
if (start.next == null) return;
Node prev = null;
Node cur = start;
Node next = cur.next;
while (next && cur != end) {
Cur.next = prev;
Prev = cur;
Cur = next;
Next = cur.next;
}
Cur.next = prev;
start = cur;
end = next;
}
Sample test cases
List, K Result
Null, 0 Null
[1] 0 [1]
[1] 1 [1]
[1] 2 [1]
[1,2] 1 [1,2]
[1,2,3], 1 [1,2,3]
[1,2,3], 2 [2,1,3]
[1,2,3], 3 [3,2,1]
[1,2,3,4,5,6], 3 [3,2,1,6,5,4]
[1,2,3,4,5,6,7], 3 [3,2,1,6,5,4,7]
[1,2,3,4,5,6,7,8], 3 [3,2,1,6,5,4,7,8]
No comments:
Post a Comment