Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
Show Similar Problems
题目意思是给一个链表,判断是不是回文,比如1->2->3->2->1就是,首先找到中点,然后对中点后面的反转,然后与头逐一比较。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverse(ListNode *head) { //翻转
ListNode *pre=NULL;
while (head)
{
ListNode *next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if (!head) return true;
ListNode* tail = head;
ListNode* mid = head;
while (tail&&tail->next)
{
tail = tail->next->next;
mid = mid->next;
}//找中点
tail = reverse(mid);
while (head!=mid)
{
if (head->val != tail->val) return false;
head = head->next;
tail = tail->next;
}
return true;
}
};