Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 4, 2013 06:57
Show Gist options
  • Save ylegall/7298993 to your computer and use it in GitHub Desktop.
Save ylegall/7298993 to your computer and use it in GitHub Desktop.
reverse a linked list, k nodes at a time.
Node reverse(Node head, int k) {
return reverse(head, k, length(head));
}
Node reverse(Node head, int k, int remaining) {
if (remaining < k) return head;
auto i = 0;
Node next, prev = null, first = head;
while (head && i < k) {
next = head.next;
head.next = prev;
prev = head;
head = next;
++i;
}
first.next = reverse(head, k, remaining - k);
return prev;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment