Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. class Solution {
  2. public ListNode reverseKGroup(ListNode head, int k) {
  3. if(head == null)
  4. return null;
  5.  
  6. this.k = k;
  7. this.next = head;
  8. Split p = nextSplit();
  9. ListNode result = p.head;
  10. while(hasNext()){
  11. Split s = nextSplit();
  12. p.end.next = s.head;
  13. p = s;
  14. }
  15. return result;
  16. }
  17.  
  18. int k;
  19. ListNode next;
  20.  
  21. boolean hasNext(){
  22. return next != null;
  23. }
  24.  
  25. Split nextSplit(){
  26. ListNode n = next;
  27. int i = 1;
  28. while(n.next != null && i < k){
  29. n = n.next; ++i;
  30.  
  31. }
  32. Split s = new Split(next, n);
  33. next = n.next;
  34. n.next = null;
  35. if(i == k)
  36. reverse(s);
  37. return s;
  38. }
  39.  
  40. void reverse(Split s){
  41. if(s.head == s.end)
  42. return;
  43.  
  44. ListNode p = s.head;
  45. ListNode n = p.next;
  46. while(n != s.end) {
  47. ListNode t = n.next;
  48. n.next = p;
  49. p = n;
  50. n = t;
  51. }
  52. n.next = p;
  53. ListNode t = s.head;
  54. s.head = s.end;
  55. s.end = t;
  56. s.end.next = null;
  57. }
  58.  
  59. class Split{
  60. ListNode head, end;
  61. Split(ListNode head, ListNode tail){
  62. this.head = head;
  63. this.end = tail;
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement