给定一个单链表,求其是否可回读,即,正着读和倒着读一样。
Input: 1->2->2->1
Output: true
思路:
遍历链表,将其节点的值存入动态数组中,最后对数组头尾的值遍历判别。
bool isPalindrome(ListNode* head) { vector<int> tmp; while (head) { tmp.push_back(head->val); head = head->next; } int i = tmp.size(); for (int j = 0; j < i/2; j++) { if (tmp[j] != tmp[i - j - 1]) return false; } return true; }
原文:https://www.cnblogs.com/luo-c/p/12876839.html