Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Reverse Nodes in k-Group (LeetCode 25) #755

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions linked_list/Reverse Nodes in k-Group (LeetCode 25)
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head); // create a dummy node to return its next (head) at the end
ListNode prev = dummy;
while (true) {
ListNode tail = prev;
int count = 0;
while (tail != null && count < k) {
tail = tail.next;
count ++;
}
if(tail == null) { // break if the current node (tail) becomes null
break;
}
ListNode start = prev.next;
ListNode nextStart = tail.next;
prev.next = reverseList(start, tail);
prev = start;
}
return dummy.next;
}

private ListNode reverseList(ListNode start, ListNode end) {
ListNode prev = end.next;
while (start != end) {
ListNode next = start.next;
start.next = prev;
prev = start;
start = next;
}
start.next = prev;

return end;
}
}