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?
Subscribe to see which companies asked this question
刚开始没住时间复杂度和空间复杂度:
/**
* 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) {
ListNode* tempHead = head;
int count = 0;
while(tempHead)
{
++count;
tempHead = tempHead->next;
}
stack<ListNode*> tempStack;
tempHead = head;
for(int i = 1; i <= count/2; ++i)
{
tempStack.push(tempHead);
tempHead = tempHead->next;
}
if(count % 2 )
tempHead = tempHead->next;
while(tempHead)
{
if(tempStack.top()->val != tempHead->val)
return false;
else
{
tempStack.pop();
tempHead = tempHead->next;
}
}
return true;
}
};
如果要求时间和空间复杂度:
将前面一般逆序,再比。空间复杂度为0(1)
/**
* 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( NULL == head || NULL == head->next )
return true;
ListNode* tempHead = head;
int count = 0;
while(tempHead)
{
++count;
tempHead = tempHead->next;
}
ListNode* pre = NULL;
ListNode* nxt = head;
for(int i = 1; i <= count/2; ++i)
{
tempHead = nxt->next;
nxt->next = pre;
pre = nxt;
nxt = tempHead;
}
if(count % 2 )
nxt = nxt->next;
while(nxt)
{
if(nxt->val != pre->val)
return false;
else
{
pre = pre->next;
nxt = nxt->next;
}
}
return true;
/*
stack<ListNode*> tempStack;
tempHead = head;
for(int i = 1; i <= count/2; ++i)
{
tempStack.push(tempHead);
tempHead = tempHead->next;
}
if(count % 2 )
tempHead = tempHead->next;
while(tempHead)
{
if(tempStack.top()->val != tempHead->val)
return false;
else
{
tempStack.pop();
tempHead = tempHead->next;
}
}
return true;*/
}
};