1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (head == null) return null; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode next = head; ListNode previous = dummy; while (next != null){ ListNode newTail = next; ListNode previous2 = next; ListNode current = next.next; int sectionLength = 0; for (int i = 0; i < k && next != null; i++){ next = next.next; sectionLength++; } if (sectionLength >= k){ for (int i = 1; i < k ; i++){ ListNode next2 = current.next; current.next = previous2; previous2 = current; current = next2; } previous.next = previous2; previous = newTail; previous.next = next; } } return dummy.next; } } |
Friday, November 13, 2015
[leetcode]Reverse Nodes in k-Group
其实while loop里面的第一个for loop可以通过%k来remove掉 下一个round做的时候聪明点吧
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment