反转

  1. // 递归
  2. ListNode reverse(ListNode head) {
  3. if (head == null || head.next == null)
  4. return head;
  5. ListNode newHead = reverse(head.next);
  6. head.next.next = head;
  7. head.next = null;
  8. return newHead;
  9. }
  10. // 迭代
  11. ListNode reverse(ListNode head) {
  12. ListNode pre = null, cur = head;
  13. while (cur != null) {
  14. ListNode ne = cur.next;
  15. cur.next = pre;
  16. pre = cur;
  17. cur = ne;
  18. }
  19. return pre;
  20. }

寻找链表中间节点

如果是奇数个节点,返回最中间的一个即可
如果是偶数个节点,返回中间靠右或靠左的那个。

  1. //使用虚拟头节点,slow最终指向中间靠左的节点
  2. if (head == null || head.next == null) return;
  3. ListNode dummy = new ListNode(-1, head);
  4. ListNode fast = dummy, slow = dummy;
  5. do {
  6. fast = fast.next.next;
  7. slow = slow.next;
  8. } while (fast != null && fast.next != null);
  1. //不使用虚拟头节点,slow最终指向中间靠右的节点
  2. if (head == null || head.next == null)
  3. return head;
  4. ListNode fast = head, slow = head;
  5. do {
  6. fast = fast.next.next;
  7. slow = slow.next;
  8. } while (fast != null && fast.next != null);

根据需求选择第一种或第二种写法!