unknown_0711

Untitled

Nov 9th, 2022
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. class Solution {
  2. public ListNode reverseKGroup(ListNode head, int k) {
  3. if (head == null || head.next == null || k == 1) return head;
  4. int count = 1;
  5. ListNode node = head, tempHead = head, tempPrev = null;
  6. while (node != null) {
  7. if (count == k) {
  8. ListNode tempLast = node.next;
  9. node.next = null;
  10. if (tempHead == head) head = reverseList(tempHead);
  11. else tempPrev.next = reverseList(tempHead);
  12. tempHead.next = tempLast;
  13. tempPrev = node = tempHead;
  14. tempHead = tempHead.next;
  15. count = 0;
  16. }
  17. count++;
  18. node = node.next;
  19. }
  20. return head;
  21. }
  22. private ListNode reverseList(ListNode head) {
  23. ListNode prev = null;
  24. ListNode curr = head;
  25. ListNode next = curr == null ? null : head.next;
  26. while (curr != null) {
  27. curr.next = prev;
  28. prev = curr;
  29. curr = next;
  30. next = next == null ? next : next.next;
  31. }
  32. return prev;
  33. }
  34. }
Add Comment
Please, Sign In to add comment