题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
思路有二:
- 将链表转换为数组。根据数组判断是否为回文串。
- 新建原链表的反序链表。迭代比较原链表与反序链表。
下面是思路一的实现:
#include <vector> class Solution { public: bool isPail(ListNode* head) { // write code here vector<int> list; auto p = head; while (p != nullptr) { list.push_back(p->val); p = p->next; } for (int i = 0, j = list.size() - 1; i <= j; i++, j--) { if (list[i] != list[j]) { return false; } } return true; } };