给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。要求用 O(n) 时间复杂度和 O(1) 空间复杂度解决。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/*
1.先遍历整个链表得出长度len
2.再将fast节点移至链表的中间
3.反转链表的后半段
4.对比链表的前半段和反转后的后半段链表值,出现不相等的就表示不是回文链表,否则就是回文链表
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *node = nullptr;
while(head) {
ListNode* tmp = head->next;
head->next = node;
node = head;
head = tmp;
}
return node;
}
bool isPalindrome(ListNode* head) {
int len = 0;
ListNode* node = head;
while(node) {
len++;
node = node->next;
}
ListNode* fast = head;
for(int i = 0; i < len/2; i++) {
fast = fast->next;
}
ListNode* new_head = reverseList(fast);
while(head && new_head) {
if(head->val != new_head->val) {
return false;
}
new_head = new_head->next;
head = head->next;
}
return true;
}
};