题目描述:(链接)
Given a singly linked list, determine if it is a palindrome.
解题思路:
使用快慢指针,找到链表的中心点,然后逆序后一半链表,最后再一一比较!
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 bool isPalindrome(ListNode* head) { 12 if (head == nullptr) return true; 13 14 ListNode *slow = head; 15 ListNode *fast = head; 16 while (fast != nullptr && fast->next != nullptr) { 17 slow = slow->next; 18 fast = fast->next->next; 19 } 20 21 // 逆序后一半链表 22 if (fast != nullptr) { 23 fast = reversedListedArray(slow->next); 24 } else { 25 fast = reversedListedArray(slow); 26 } 27 28 slow = head; 29 while (slow != nullptr && fast != nullptr) { 30 if (slow->val != fast->val) { 31 return false; 32 } 33 slow = slow->next; 34 fast = fast->next; 35 } 36 37 return true; 38 } 39 private: 40 ListNode *reversedListedArray(ListNode *head) { 41 if (head == nullptr) return head; 42 43 ListNode dummy(-1); 44 dummy.next = head; 45 ListNode *prev = dummy.next; 46 ListNode *cur = prev->next; 47 while (cur != nullptr) { 48 prev->next = cur->next; 49 cur->next = dummy.next; 50 dummy.next = cur; 51 cur = prev->next; 52 } 53 return dummy.next; 54 } 55 };