Skip to content

Instantly share code, notes, and snippets.

@daifu
Created May 26, 2013 06:15
Show Gist options
  • Select an option

  • Save daifu/5651878 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5651878 to your computer and use it in GitHub Desktop.
Reverse Nodes in k-Group
/*
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Algorithm:
It is a recursive algorithm with sub-problem: reverse linked list with length upto k
Since the subproblem is pretty obvious, and the it has the main
problem is how to figure out this is a recursive problem and connect
different sub group of reversed linked list.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if(k == 0 || k == 1) return head;
if(head == null) return null;
int total = getLen(head);
return swapUntilK(k, head, total);
}
public ListNode swapUntilK(int k, ListNode head, int total) {
ListNode front = head;
ListNode back = null;
int count = k;
total -= count;
if(total < 0) return head;
// reverse the linked list upto k
while(count > 0 && front != null) {
ListNode tmp = front;
front = front.next;
tmp.next = back;
back = tmp;
count--;
}
if(front != null) {
// connect to the next node
head.next = swapUntilK(k, front, total);
}
return back;
}
public int getLen(ListNode head) {
int count = 0;
while(head != null) {
head = head.next;
count++;
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment