25. Palindrome Linked List
02 Jul 2020 | Daily Algorithms
/**
* 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:
bool isPalindrome(ListNode* head) {
ListNode* p = head;
vector<int> stack;
int size_ = 0;
while(p)
{
stack.push_back(p->val);
p=p->next;
size_++;
}
int i = 0;
p=head;
while(i<size_)
{
if(p->val == stack.back())
{
stack.pop_back();
p = p->next;
i++;
}
else
{
return false;
}
}
return true;
}
};
/**
* 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:
bool isPalindrome(ListNode* head) {
ListNode* p = head;
vector<int> stack;
int size_ = 0;
while(p)
{
stack.push_back(p->val);
p=p->next;
size_++;
}
int i = 0;
p=head;
while(i<size_)
{
if(p->val == stack.back())
{
stack.pop_back();
p = p->next;
i++;
}
else
{
return false;
}
}
return true;
}
};
Comments