234. Palindrome Linked List
problem description
Input: 1->2
Output: falseInput: 1->2->2->1
Output: truealgorithm thought
code
/**
* 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) {
stack<int> st;
ListNode* fast=head,*slow=head;
while(fast!=NULL&&fast->next!=NULL){
st.push(slow->val);
slow=slow->next;
fast=fast->next->next;
}
if(fast)
slow=slow->next;
while(slow){
if(slow->val!=st.top())
return false;
slow=slow->next;
st.pop();
}
return true;
}
};algorithm analysis
Last updated