-
-
Save InterviewBytes/6e1322d883bfc6539bc8a27d78f13fc3 to your computer and use it in GitHub Desktop.
Reverse Nodes in k-Group
This file contains 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
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains 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
package com.interviewbytes.linkedlists; | |
public class ReverseKGroup { | |
public ListNode reverseKGroup(ListNode head, int k) { | |
if (head == null) return null; | |
int count = k; | |
ListNode current = head; | |
while (count > 0 && current != null) { | |
current = current.next; | |
count--; | |
} | |
if (count > 0) return head; | |
ListNode newHead = null; | |
current = head; | |
count = k; | |
while (count > 0 && current != null) { | |
ListNode next = current.next; | |
current.next = newHead; | |
newHead = current; | |
current = next; | |
count--; | |
} | |
if (current != null) head.next = reverseKGroup(current, k); | |
return newHead; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment