&LeetCode234& 回文链表

题目

请判断一个链表是否为回文链表。

示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true

来源:力扣(LeetCode

思路

首先,按顺序把所有的结点值都存入到一个栈 stack 里;
然后,利用栈的后入先出的特性,可以按顺序从末尾取出结点值;
此时,再遍历一遍链表,就可以比较回文对应位置;
最后,如果值不同直接返回 false 。

C++代码

class Solution {
public:
    bool isPalindrome(ListNode* head) 
    {
        ListNode *cur = head;
        stack<int> st;
        while (cur)
        {
            st.push(cur -> val);
            cur = cur -> next;
        }
        while (head)
        {
            int t = st.top();
            st.pop();
            if (head -> val != t)
                return false;
            head = head -> next;
        }
        return true;
    }
};
发布了51 篇原创文章 · 获赞 20 · 访问量 2081

猜你喜欢

转载自blog.csdn.net/weixin_40482465/article/details/104500150
今日推荐