Palindrome Linked List
题目描述:
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:
bool isPalindrome(ListNode* head) { if (head == NULL || head->next == NULL) return true; ListNode *fast = head; ListNode *slow = head; while (fast->next != NULL) { fast = fast->next; slow = slow->next; if (fast->next != NULL) fast = fast->next; } fast = reverseList(slow); ListNode *p = head; while (p != slow && p->val == fast->val) { p = p->next; fast = fast->next; } if (p == slow) return true; else return false; }
反转单链表的代码见这里