相关教程 —<Click

哑结点 —<Click

反转链表

递归

Linked List 链表 - 图1

  1. ListNode reverse(ListNode head) {
  2. if (head.next == null) return head;
  3. ListNode last = reverse(head.next);
  4. head.next.next = head;
  5. head.next = null;
  6. return last;
  7. }

非递归

  1. //反转以 a 为头结点的链表
  2. ListNode reverse(ListNode a) {
  3. ListNode pre, cur, nxt;
  4. pre = null; cur = a; nxt = a;
  5. while (cur != null) {
  6. nxt = cur.next;
  7. // 逐个结点反转
  8. cur.next = pre;
  9. // 更新指针位置
  10. pre = cur;
  11. cur = nxt;
  12. }
  13. // 返回反转后的头结点
  14. return pre;
  15. }

Leetcode

234. 回文链表

请判断一个链表是否为回文链表。

示例 1: 输入: 1->2 输出: false

示例 2: 输入: 1->2->2->1 输出: true

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }

        if(fast != null){
            slow = slow.next;
        }

        slow = reverse(slow);   //重定向
        fast = head;

        while(slow != null){
            if(fast.val != slow.val){
                return false;
            }
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }
    public ListNode reverse(ListNode head){
        ListNode pre, cur, next;
        pre = null; cur = head; next = head;

        while(cur != null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }
}

https://leetcode-cn.com/problems/palindrome-linked-list/solution/di-gui-zhan-deng-3chong-jie-jue-fang-shi-zui-hao-d/