• 判定是否是回文数

例子:

输入: 121
输出: true
输入: -121
输出: false
bool isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0)){
            return false;
        }
        int r = 0;
        while(x > r){//12321
            r = r*10 + x % 10;//1,12,123
            x /= 10;//1232,123,12
        }
        return x == r || x == r/10;//12=123/10
    }
  • 判定是否是回文链表

解析:快慢指针找到链表的中点。12321,slow指到3,让fast指向slow.next为2.反转后半部分链表。再进行依次比对

public boolean isPalindrome(ListNode head) {
        // 边界条件:空链表或只有一个节点的链表
        if (head == null || head.next == null) {
            return true;
        }

        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode slow = dummyNode;
        ListNode fast = dummyNode;

        // 慢指针一次走一步,快指针一次走两步,当快指针走到终点,慢指针刚好处于中点位置
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // fast指针置于下半段链表的起点
        fast = slow.next;
        // 断开前后两个链表
        slow.next = null;
        // slow指针置于前半段链表的起点
        slow = dummyNode.next;

        // 反转后半段链表
        ListNode pre = null; // 保存指针前一节点的信息,用于反转
        while (fast != null) {
            ListNode nextTemp = fast.next;
            fast.next = pre;
            pre = fast;
            fast = nextTemp;
        }

        // 前后半链表逐一比较,当链表长度为奇数时前半段链表长度比后半段多1,所以以后半段为准
        while (pre != null) {
            if (slow.val != pre.val) {
                return false;
            }
            slow = slow.next;
            pre = pre.next;
        }
        return true;
    }