Palindrome Linked List
题目:
Implement a function to check if a linked list is a palindrome.
分析:
本身逻辑不难,但是mock得时候reverseList居然写错了,写成了while(head != NULL), 然后死循环了。。。明明后面要取head->next->next的,怎么能取得出来呢!
正确写法是while(head->next != NULL)因为你实际上移动的是head->next这个节点呀,科科!
解法:
class Solution {
public:
/**
* @param head a ListNode
* @return a boolean
*/
ListNode* reverseList(ListNode* head) {
ListNode dummy(0);
dummy.next = head;
while (head->next != NULL) {
ListNode* next = head->next;
head->next = next->next;
next->next = dummy.next;
dummy.next = next;
}
return dummy.next;
}
bool isPalindrome(ListNode* head) {
// Write your code here
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;
}
ListNode* newHead = slow->next;
slow->next = NULL;
ListNode* head2 = reverseList(newHead);
while (head != NULL && head2 != NULL) {
if (head->val != head2->val) {
return false;
}
head = head->next;
head2 = head2->next;
}
return true;
}
};