Created
November 4, 2013 06:57
-
-
Save ylegall/7298993 to your computer and use it in GitHub Desktop.
reverse a linked list, k nodes at a time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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