Created
May 14, 2017 13:54
-
-
Save thanlau/4b2a51e373661d39896f92b471175244 to your computer and use it in GitHub Desktop.
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
/** | |
* 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