leetcode9回文数和leetcode234回文链表
一、回文数
1.题目链接
https://leetcode-cn.com/problems/palindrome-number/
2.题目描述
示例 1:
输入: 121 输出: true
示例 2:
输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
3.题目分析
根据题目描述,回文数是指正序和倒序读都是一样的整数。那么可以将数字本身反转,然后将反转的数字和原始数字比较,若完全相同,该数就是回文数。
4.代码实现
bool isPalindrome(int x){ long res = 0; int data = x; while (x > 0) { res = res * 10 + x % 10; x /= 10; } if (res == data) return true; else return false; }
5.提交记录
执行用例用时
二、回文链表
1.题目链接
https://leetcode-cn.com/problems/palindrome-linked-list/
2.题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2输出: false
示例 2:
输入: 1->2->2->1输出: true
3.题目分析
根据描述,回文链表和回文数类似,回文链表即正序和倒序读都是一样的链表。可以只反转一半的链表,用快慢指针来实现,先找到链表的中点,然后将链表后半部分反转,最后将反转的链表和原始链表比较。
4.代码实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool isPalindrome(struct ListNode* head){ if (head == NULL || head->next ==NULL) return true; struct ListNode *fast = head; struct ListNode *slow = head; struct ListNode *pre = NULL; //快慢指针 找到链表的中点 while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; } //将slow之后的两边反转 while (slow != NULL) { struct ListNode *next = slow->next; slow->next = pre; pre = slow; slow = next; } //前后链表进行比较 while (head != NULL && pre != NULL) { printf("head->val = %d, pre->val = %d\n", head->val, pre->val); if (head->val != pre->val) return false; head = head->next; pre = pre->next; } return true; }
5.提交记录
执行用例用时
stay hungry, stay foolish