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

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

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) {
        // write code here
        if (!head || !head->next)
            return head;
        ListNode* cur = head;
        ListNode* c = head;
        stack<int> s;
        while (cur)
        {
            s.push(cur->val);
            cur = cur->next;
        }
        while (c)
        {
            if (c->val != s.top())
                return false;
            c = c->next;
            s.pop();
        }
        return true;
    }
  
  
  
        /*
        //从后往前倒放进辅助向量
    bool isPail(ListNode* head) {
        if (!head || !head->next)
            return true;
        ListNode* cur = head;
        store(head);
        for (int i=0; i < sto.size(); i++)
        {
            if (cur->val != sto[i])
                return false;
            cur = cur->next;
        }
        return true;
    }
    void store(ListNode* head)
    {
        if (!head)
            return;
        store(head->next);
        sto.push_back(head->val);
    }
    vector<int> sto;
    	*/
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务