Palindrome Linked List

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;
	}
};
posted @ 2015-08-12 21:14  影湛  阅读(108)  评论(0编辑  收藏  举报