1、栈
bool isPalindrome(ListNode* head) {
stack<ListNode*> st;
ListNode* cur = head;
while (cur != NULL) {
st.push(cur);
cur = cur->next;
}
cur = head;
while (cur != NULL) {
if (cur->val != st.top()->val) {
return false;
}
st.pop();
cur = cur->next;
}
return true;
}
时间O(n),空间O(n)
2、快慢指针,慢指针反转前半段
bool isPalindrome(ListNode* head) {
if (head->next == NULL) {
return true;
}
//不还原
ListNode* pre = NULL, * slow = head, * next = NULL;
ListNode* fast = head;
ListNode* first, * second;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
next = slow->next;
slow->next = pre;
pre = slow;
slow = next;
}
if (fast!= NULL) {//奇数个节点
slow= slow->next;
}
while (pre != NULL) {
if (slow->val != pre->val) {
return false;
}
slow = slow->next;
pre = pre->next;
}
return true;
}
时间O(n)`,空间O(1)``
![在这里插入图片描述](https://img-blog.csdnimg.cn/dccad657b7a44657a3c2caf8f64ceebc.png)
第二种方法参考了官方题解下弹弹霹雳的解法。