一种是直接将元素压入栈 然后依次退栈和链表相比
第二种是快慢指针,fast两格一跳,slow 一格一跳。在后半压入栈。与链表相比
第三种 直接在后半段取反 比较完后还原
class Solution {
public:
ListNode* reverseList(ListNode* head) {
struct ListNode *p = NULL;
struct ListNode *q;
while (head) {
q = head;
head = head->next;
q->next = p;
p = q;
}
return p;
}
bool isPalindrome(ListNode* head) {
if (head == NULL) return true;
if (head->next == NULL) return true;
if (head->next->next == NULL) {
if (head->val == head->next->val)
return true;
else return false;
}
ListNode *fast = head;
ListNode *slow = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
if (fast->next !=NULL) {
fast = fast->next;
}
ListNode *newhead = slow->next;
slow->next = NULL;
newhead = reverseList(newhead);
ListNode *p = head;
ListNode *q = newhead;
while (p != NULL && q != NULL) {
if (p->val != q->val)
return false;
p = p->next;
q = q->next;
}
return true;
}
};