请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
一看到回文,我立刻就想到了栈,想把链表所有的数存入栈,再一一对比
/**
* 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==NULL)
{
return true;
}
if(head->next==NULL)
{
return true;
}
ListNode *p=head,*q=head;;
stack<int>s1;
while(p!=NULL)
{
s1.push(p->val);
p=p->next;
}
while(!s1.empty())
{
if(s1.top()==q->val)
{
s1.pop();
q=q->next;
}
else
{
return false;
}
}
return true;
}
};