Leetcode9-回文数

题目链接:9. 回文数 - 力扣(LeetCode)

这道题目比较简单,但需要注意的是用C语言时,整数溢出的情况

代码:

bool isPalindrome(int x) {
    if(x == 0) return true;
    if (x < 0) return false;

    int num = 0;
    int y = x;
    while(y > 0) {
        if (num > INT_MAX/10 || (num == INT_MAX/10 && (y % 10 > 7))) {
            return false;
        }
        num = num*10 + y % 10;
        y /= 10;
    }
    if (x == num) {
        return true;
    }else{
        return false;
    }
}

LeetCode 234题回文链表有多种解法,以下为你介绍几种常见的解法: ### 解法一:将链表复制到数组里再从两头比对 将链表元素复制到数组中,然后使用双指针从数组的两端向中间遍历,比较对应元素是否相等。如果在遍历过程中发现不相等的元素,则链表不是回文链表;如果遍历完整个数组都没有发现不相等的元素,则链表是回文链表。 ```cpp #include <vector> class Solution { public: bool isPalindrome(ListNode* head) { std::vector<int> listvec; // 把链表中元素都插入数组 while (head != nullptr) { listvec.push_back(head->val); head = head->next; } // 一个迭代器从头,一个迭代器从尾 auto it_head = listvec.begin(); auto it_back = listvec.end() - 1; // 若迭代器相遇了则说明都检查完了,可以返回true while (it_back - it_head > 0) { // 检查到值不相等就返回false if ((*it_head++) != (*it_back--)) return false; } return true; } }; ``` ### 解法二:递归法 递归地遍历链表,同时使用一个指针从链表头开始比较。递归过程中,先递归到链表的末尾,然后在回溯的过程中与链表头指针指向的元素进行比较。 ```cpp class Solution { ListNode* frontPointer; public: bool recursivelyCheck(ListNode* currentNode) { if (currentNode != nullptr) { if (!recursivelyCheck(currentNode->next)) { return false; } if (currentNode->val != frontPointer->val) { return false; } frontPointer = frontPointer->next; } return true; } bool isPalindrome(ListNode* head) { frontPointer = head; return recursivelyCheck(head); } }; ``` ### 解法三:快慢指针 + 反转链表 使用快慢指针找到链表的中点,然后将链表的后半部分反转,最后比较前半部分和反转后的后半部分是否相等。 ```cpp class Solution { public: bool isPalindrome(ListNode* head) { if (head == nullptr) return true; // 找到前半部分链表的尾节点并反转后半部分链表 ListNode* firstHalfEnd = endOfFirstHalf(head); ListNode* secondHalfStart = reverseList(firstHalfEnd->next); // 判断是否回文 ListNode* p1 = head; ListNode* p2 = secondHalfStart; bool result = true; while (result && p2 != nullptr) { if (p1->val != p2->val) result = false; p1 = p1->next; p2 = p2->next; } // 还原链表并返回结果 firstHalfEnd->next = reverseList(secondHalfStart); return result; } private: ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr != nullptr) { ListNode* nextTemp = curr->next; curr->next = prev; prev = curr; curr = nextTemp; } return prev; } ListNode* endOfFirstHalf(ListNode* head) { ListNode* fast = head; ListNode* slow = head; while (fast->next != nullptr && fast->next->next != nullptr) { fast = fast->next->next; slow = slow->next; } return slow; } }; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

映秀小子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值