题目链接:LC 234. 回文链表
2020.10.10第一次解答:
解题思路
申请栈空间存储链表中所有的val值,再遍历链表逐个比较。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> nums;
ListNode* cur = head;
while (cur) {
nums.push(cur->val);
cur = cur->next;
}
cur = head;
while (cur) {
if (cur->val != nums.top()) return false;
cur = cur->next;
nums.pop();
}
return true;
}
};