题解 | #牛群编号的回文顺序#
牛群编号的回文顺序
https://www.nowcoder.com/practice/e41428c80d48458fac60a35de44ec528
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return bool布尔型
*/
//用栈存一半然后出栈比较另一半
bool isPalindrome(ListNode* head) {
// write code here
if(!head) return false;
if(!head->next) return true;
std::stack<ListNode*> s;
int i=0;
ListNode *p=head;
while(p){ //统计有多少节点
i++;
p=p->next;
}
p=head;
int j=i/2;
while(j--){
s.push(p);
p=p->next;
}
if(i%2){
p=p->next;
}
j=i/2;
while(j--){
if(s.top()->val!=p->val) return false;
cout<<p->val<<','<<s.top()->val<<"--";
s.pop();
p=p->next;
}
if(!s.empty()||p) return false;
return true;
}
};
阿里云成长空间 747人发布