题目描述
给定一个链表,请判断该链表是否为回文结构。
示例
输入
[1,2,2,1]
返回值
true
思路描述
可以理解回文结构即为从头部开始访问和从尾部开始访问的结果是一样的,故可以将链表全都压入栈中,然后和原来的链表的顺序中一个一个作比较,如果全都相同,那么就是回文结构
代码描述
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
ListNode* curr = head;
stack<int> s;
while(curr){
s.push(curr->val);
curr = curr->next;
}
curr = head;
while(curr){
if(curr->val != s.top())
return false;
s.pop();
curr = curr->next;
}
return true;
}
};