编写一个函数,检查输入的链表是否是回文的。
示例 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) {
stack<int> temp;
ListNode *p=head;
while (p!=NULL){
temp.push(p->val);
p=p->next;
}
ListNode *q=head;
while(q!=NULL){
if (q->val!=temp.top()){
return false;
}
else{
q=q->next;
temp.pop();
}
}
return true;
}
};