Leetcode 234.Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
我们使用快慢指针找中点的原理是fast和slow两个指针,每次快指针走两步,慢指针走一步,等快指针走完时,慢指针的位置就是中点。我们还需要用栈,每次慢指针走一步,都把值存入栈中,等到达中点时,链表的前半段都存入栈中了,由于栈的后进先出的性质,就可以和后半段链表按照回文对应的顺序比较了。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow = head, *fast = head;
stack<int> s;
s.push(head->val);
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
s.push(slow->val);
}
if (!fast->next) s.pop();
while (slow->next) {
slow = slow->next;
int tmp = s.top(); s.pop();
if (tmp != slow->val) return false;
}
return true;
}
};
O(n) O(1)
/**
* 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;
ListNode * slow = head;
while(fast->next!=NULL && fast->next->next !=NULL){
fast = fast->next->next;
slow = slow->next;
}
ListNode* rev = reverse(slow->next);
while(rev != NULL){
if(rev->val != head->val) return false;
rev=rev->next;
head=head->next;
}
return true;
}
ListNode* reverse(ListNode * &head){
ListNode * prev= NULL;
while(head){
ListNode * temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
return prev;
}
};
REF: