Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
题目大意:
判断链表是否是回文。尝试在O(n) time和O(1) space条件下解决。
解题思路:
肯定使用递归,但是递归时只能回溯到上一个节点,而从头结点向下同时遍历无法在在递归内完成,所以需要借助外部变量,当每一次回溯时移动到下一位。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* _node;
bool helper(ListNode* tmp){
if(tmp == nullptr)
return true;
auto ans = helper(tmp->next) && (tmp->val == _node->val);
_node = _node->next;
return ans;
}
public:
bool isPalindrome(ListNode* head) {
if(head == nullptr || head->next==nullptr)
return true;
_node = head;
return helper(head);
}
};