Skip to content

Instantly share code, notes, and snippets.

@thanlau
Created May 14, 2017 13:54
Show Gist options
  • Save thanlau/4b2a51e373661d39896f92b471175244 to your computer and use it in GitHub Desktop.
Save thanlau/4b2a51e373661d39896f92b471175244 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param k an integer
* @return a ListNode
*/
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null){
return null;
}
Stack<ListNode> stack = new Stack<ListNode>();
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
ListNode next = dummy.next;
while(next!=null){
for(int i = 0; i<k && next != null; i++){
stack.push(next);
next = next.next;
}
if(stack.size() !=k) return dummy.next;
while(stack.size() !=0){
cur.next = stack.pop();
cur = cur.next;
}
cur.next = next;
}
return dummy.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment