您的位置:首页 > 其它

Palindrome Linked List

2015-08-12 21:14 477 查看

Description:


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?


Solution:

class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head)  return true;
auto slow = head;
auto fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
// reverse right half of list
ListNode dummy(0);
while (slow) {
auto next = slow->next;
slow->next = dummy.next;
dummy.next = slow;
slow = next;
}
auto rev = dummy.next;
while (rev) {
if (rev->val != head->val)  return false;
rev = rev->next;
head = head->next;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: