25 k个一组翻转链表

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode reverseKGroup(ListNode head, int k) {
  13. if (head == null)
  14. return head;
  15. if (k <= 0)
  16. return head;
  17. ListNode dummy = new ListNode(-1);
  18. dummy.next = head;
  19. ListNode pre = dummy;
  20. ListNode end = dummy;
  21. ListNode start = pre.next;
  22. while (end.next != null) {
  23. for (int i = 0; i < k; i++) {
  24. if (end == null)
  25. return dummy.next;
  26. end = end.next;
  27. }
  28. if (end == null)
  29. return dummy.next;
  30. // 将链先断开
  31. ListNode next = end.next;
  32. end.next = null;
  33. pre.next = reverse(start);
  34. // 将链再接上
  35. start.next = next;
  36. pre = start;
  37. end = start;
  38. start = next;
  39. }
  40. return dummy.next;
  41. }
  42. private ListNode reverse(ListNode head) {
  43. ListNode p, q;
  44. // 头插法
  45. ListNode phead = new ListNode(-1);
  46. phead.next = null;
  47. p = head;
  48. while (p != null) {
  49. q = p.next;
  50. p.next = phead.next;
  51. phead.next = p;
  52. p = q;
  53. }
  54. return phead.next;
  55. }
  56. }