题目
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:

输入:head = [1,2,2,1]
输出:true
示例 2:

输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindrome-linked-list
题解
解题思路:用栈比较,时间复杂度O(n)
/**
* 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) {
int len=0;
ListNode* p=head;
while(p){
len++;
p=p->next;
}
if(len<2) return true;
else{
p=head;
stack<ListNode*> a;
for(int i=0;i<len/2;i++){
a.push(p);
p=p->next;
}
if(len%2!=0) p=p->next;
while(!a.empty()&&p){
if(p->val!=a.top()->val) return false;
a.pop();
p=p->next;
}
return true;
}
}
};