描述
给定一个链表,请判断该链表是否为回文结构。回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数
0
≤
n
≤
1
0
5
0 \le n \le 10^5
0≤n≤105 ,链表中每个节点的值满足
∣
v
a
l
∣
≤
1
0
7
|val| \le 10^7
∣val∣≤107
示例1
输入:{1}
返回值:true
示例2
输入:{2,1}
返回值:false
说明:2->1
示例3
输入:{1,2,2,1}
返回值:true
说明:1->2->2->1
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
if(head==nullptr||head->next==nullptr)
return true;
stack<ListNode*> st;
ListNode *p=head;
while(p){
st.push(p);
p=p->next;
}
p=head;
while(p){
if(p->val!=(st.top()->val))
return false;
st.pop();
p=p->next;
}
return true;
}
};