请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head) return true;
if (!head->next) return true;
//快慢指针找中间节点
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
//反转后半部分链表,slow指向后半部分链表的开始
ListNode* prev = nullptr;
while(slow) {
ListNode* later = slow->next;
slow->next = prev;
prev = slow;
slow = later;
}
//判断两链表是否相同
ListNode* head1 = head;
ListNode* head2 = prev;
while(head1 && head2) {
if (head1->val != head2->val)
return false;
head1 = head1->next;
head2 = head2->next;
}
return true;
}
};
解法二:递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* tmp;
bool Helper(ListNode* node) {
if (!node)
return true;
bool res = Helper(node->next) ? node->val == tmp->val : false;
tmp = tmp->next;
return res;
}
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next)
return true;
tmp = head;
return Helper(head);
}
};