题解一:利用stack来判断回文,这里注意奇偶的处理,利用快慢指针找中点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
stack<int> ST;
ListNode * slow = head;
ListNode * fast = head->next;
while(fast && fast->next){
ST.push(slow->val);
cout<<slow->val<<endl;
fast = fast->next->next;
slow= slow->next;
}
if(fast){
ST.push(slow->val);
}
slow = slow->next;
while(slow){
int x = ST.top();
ST.pop();
if(slow->val != x){
return false;
}
slow = slow->next;
}
return true;
}
};
题解二:
将后半段进行翻转,然后比较。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL){
return true;
}
ListNode * fast = head->next;
ListNode * slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
if(fast){
slow = slow->next;
}
ListNode * rhead = reverse(slow);
ListNode * lcurr = head, * rcurr = rhead;
while(rcurr){
if(lcurr->val != rcurr->val){
return false;
}
lcurr = lcurr->next;
rcurr = rcurr->next;
}
return true;
}
private:
ListNode * reverse(ListNode *phead){
ListNode * prev = NULL;
ListNode * cur = phead;
while(cur){
ListNode *tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
};