题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 the head * @return bool布尔型 */ bool isPail(ListNode* head) { // write code here stack<int> stk; ListNode* p = head; int len = 0; while(p != nullptr){ len++; p = p->next; } p = head; int temp = len / 2; while(temp--){ stk.push(p->val); p = p->next; } if(len % 2 == 1){ p = p->next; } while(p!=nullptr && !stk.empty()){ if(p->val == stk.top()){ p = p->next; stk.pop(); } else return false; } return true; } };