1.描述
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?
2.分析
将链表后半部分全部翻转;
后半部和前半部分一一对比,若两个节点不相等则不是回文;
还原链表:将后半部分全部翻转。
3.代码
/**
* 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 *slow = head, *fast = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
slow->next = reverseList(slow->next);
ListNode* pos = slow->next;
bool ans = true;
while (pos != NULL) {
if (head->val != pos->val) {
ans = false;
}
pos = pos->next;
head = head->next;
}
slow->next = reverseList(slow->next);
return ans;
}
ListNode* reverseList(ListNode* &head) {
ListNode* pos = head;
ListNode* tmp;
head = NULL;
while (pos != NULL) {
tmp = pos;
pos = pos->next;
tmp->next = head;
head = tmp;
}
return head;
}
};
网友评论