24. 两两交换链表中的节点

  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 swapPairs(ListNode head) {
  13. if (head == null)
  14. return head;
  15. ListNode dummy = new ListNode(-1);
  16. dummy.next = head;
  17. ListNode pre = dummy;
  18. ListNode end = dummy;
  19. ListNode start = pre.next;
  20. while (end.next != null) {
  21. for (int i = 0; i < 2; i++) {
  22. if (end == null)
  23. return dummy.next;
  24. end = end.next;
  25. }
  26. if (end == null)
  27. return dummy.next;
  28. // 将链先断开
  29. ListNode next = end.next;
  30. end.next = null;
  31. pre.next = reverse(start);
  32. // 将链再接上
  33. start.next = next;
  34. pre = start;
  35. end = start;
  36. start = next;
  37. }
  38. return dummy.next;
  39. }
  40. private ListNode reverse(ListNode head) {
  41. ListNode p, q;
  42. // 头插法
  43. ListNode phead = new ListNode(-1);
  44. phead.next = null;
  45. p = head;
  46. while (p != null) {
  47. q = p.next;
  48. p.next = phead.next;
  49. phead.next = p;
  50. p = q;
  51. }
  52. return phead.next;
  53. }
  54. }