Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
进阶:你能只用O(n)的时间复杂度和O(1)的空间复杂度吗?
题目不难,可是我想了很久都只能做到O(n)的时间复杂度,并不能做到O(1)的空间复杂度。。。我的思路是把前n/2个节点压入栈,然后依次出栈,与后n/2个节点比对即可。
/**
* 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||!head->next) return true;
int length=0;
ListNode* temp=head;
while(temp)
{
length++;
temp=temp->next;
}
stack<int> stk;
for(int i=0;i<(length+1)/2;i++)
{
stk.push(head->val);
head=head->next;
}
if(length%2!=0) stk.pop();
while(!stk.empty())
{
if(stk.top()!=head->val) return false;
stk.pop();
head=head->next;
}
return true;
}
};