题目
请判断一个链表是否为回文链表。
解题思路
反转链表的后半段。
C++代码
/** * 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; ListNode* fast = head; while(fast->next) { slow = slow->next; fast = fast->next; if(fast->next) fast = fast->next; } fast = slow->next; slow->next = NULL; while(fast) { ListNode *p = fast->next; fast->next = slow; slow = fast; fast = p; } fast = slow; slow = head; while(slow && fast) { if(slow->val != fast->val) return false; fast = fast->next; slow = slow->next; } return true; } };