设计一种方式检查一个链表是否为回文链表。
样例
1->2->1
就是一个回文链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param head: A ListNode.
* @return: A boolean.
*/
bool isPalindrome(ListNode * head) {
stack<int> tmp;//使用一个栈作为辅助
ListNode* p1=head, *p2=head;
while(p1)//依次入栈
{
tmp.push(p1->val);
p1 = p1->next;
}
while(p2)//依次出栈,与原链表的值对比
{
if (p2->val != tmp.top()) //一旦不相等就退出
break;
p2 = p2->next;
tmp.pop();
}
if (p2 == NULL) //表示所有都相等
return true;
return false;
}
};