题解 | #判断一个链表是否为回文结构#

判断一个链表是否为回文结构

http://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) {
        stack<int> stk{};
        ListNode* cur=head;
        while(cur!=nullptr){
            stk.push(cur->val);
            cur=cur->next;
        }
        cur=head;
        while(cur!=nullptr){
            int rear=stk.top();
            stk.pop();
            if(cur->val!=rear) return false;
            cur=cur->next;
        }
        return true;
    }
};



全部评论

相关推荐

千千倩倩:简历问题有点多,加v细聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务