题解 | NO.13#判断一个链表是否为回文结构#3.6
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head * @return bool布尔型 */ bool isPail(ListNode* head) { // 用数组存储整个链表,再用两个指针从头、尾同时向中间遍历 if(head == NULL || head->next == NULL){ return true; } int List[100000]; int i = 0; ListNode *p = head; while(p){ List[i] = p->val; p = p->next; ++i; } i--; //开始这里忘记减1了,导致right跑到了数组最后一个值的后一位 int left = 0, right = i; while(List[left] == List[right] && left < right){ left++; right--; } if(abs(left - right) <= 1){ return true; }else{ return false; } } };