只会先化为数组的做法,看答案了解了一下递归做法,不过空间复杂度没区别,但是挺巧妙的。
cpp
/**
* 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) {}
* };
*/
class Solution {
public:
ListNode *h;
bool isPalindrome(ListNode* head) {
h=head;
return dg(head);
}
bool dg(ListNode* node){
node=node->next;
if(node==NULL) return 1;
bool b=dg(node);
if(node->val!=h->val) return 0;
h=h->next;
return b;
}
};
看了答案中空间复杂度O(1)的做法,其实难想到,就是用快慢指针找到中间点,之后将后半段反转。