用栈记录当前元素是否出现过,出现过则出栈
/**
* 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) {
// 先看链表长度,分情况讨论
ListNode*p = head;
int n = 0;
while(p){
p=p->next;
n++;
}
if(n<=1){
return true;
}
cout<<n<<" "<<n/2+1<<endl;
stack<int> s;
int count = 0; //
while(head){
count++;
if(s.empty()){
s.push(head->val);
}else{
if(n%2!=0){
if(count == n/2+1){
cout<<"跳过:"<<count<<head->val<<endl;
}else{
if(s.top()==head->val){
s.pop();
}else{
s.push(head->val);
}
}
}else{
if(s.top()==head->val){
s.pop();
}else{
s.push(head->val);
}
}
}
head = head->next;
}
if(s.empty()){
return true;
}else{
return false;
}
}
};