1.题目
Given a singly linked list, determine if it is a palindrome.
例如:
1->2->3->2->1 回文
1->2->2->1 回文
1->2->3 不回文
2.分析
判断回文列表与判断回文字符串的差别在于:列表是单向的,无法从列尾反向遍历。所以我们需要翻转字符串。
假设列表
长度为偶数 分为AB段
长度为奇数 分为AXB段
我们只需要翻转B段,然后判断翻转后的B段与A段是否一致。
如何确定B段?
两个指针slow,fast。slow每次走一步,fast每次走两步。当fast走到末尾,slow指向B段的开头。
3.代码
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL)
return true;
ListNode* slow = head;
ListNode* fast = head;
while (fast->next!=NULL&&fast->next->next!=NULL) {
slow = slow->next;
fast = fast->next->next;
}
slow = slow->next;
slow = reverseL(slow);
fast = head;
while (slow) {
if (slow->val != fast->val)
return false;
slow = slow->next;
fast = fast->next;
}
return true;
}
ListNode* reverseL(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* pre = NULL;
while (head) {
ListNode* pNext = head->next;
head->next = pre;
pre = head;
head = pNext;
}
return pre;
}
};