剑指offer——面试案例

剑指offer——面试案例

面试题49:把字符串转换为整数

**补:**C++中成员变量的初始化顺序只与它们在类声明中的顺序有关,而与在初始化列表中的顺序无关

/*考虑空指针,空字符串,正负号,溢出等情况,参考atoi函数*/
enum Status{kValid = 0,kInvald};
int g_nStatus = kVlaid;
int StrToInt(const char *str)
{
    f_nStatus = kInvalid;
    if (str!-NULL && *str!='\0')
    {
        bool minus = false;
        if (*str=="+")
            str++;
        else if (*str=="-")
        {
            str++;
            minus = true;
        }
        if (*str!='\0')
            num = StrToIntCore(str,minus);
    }
    return (int)num;
}
long long StrToIntCore(const char* digit,bool minus)
{
    long long num = 0;
    while (digit !='\0')
    {
        if (*digit >='0' && *digit <='9')
        {
            int flag = minus ?-1:1;
            num = num*10+flag*(*digit-'0');
            if ((!minus && num>0x7FFFFFFF) 
                || (minus && num <(signed int)0x80000000))
                {
                    num = 0;
                    break;
                }
            digit++;
        }
        else
        {
            num = 0;
            break;  
        }
    }
    if (*digit=='\0')
        g_nStatus = kValid;
    return num;
}

面试题50:树中两个结点的最低公共祖先

//获取从根结点到指定结点的路径
bool GetNodePath(TreeNode* pRoot,TreeNode* pNode,list<TreeNode*> &path)
{
    if (pRoot == pNode)
        return true;
    path.push_back(pRoot);
    bool found = false;
    vector<TreeNode*>::iterator i = pRoot>m_pChildren.begin();
    while (!found && i<pRoot->m_vChildren.end())
    {
        found = GetNodePath(*i,pNode,path);
        ++i;
    }
    if (!found)
        path.pop_back();
    return found;
}
//得到路径的最后一个公共结点
TreeNode* GetLastCommonNode(const list<TreeNode*>& path1,const list<TreeNode*>& path2)
{
    list<TreeNode*>::const_iterator iterator1 = path1.begin();
    list<TreeNode*>::const_iterator iterator2 = path2.begin();
    TreeNode* pLast == NULL;
    while(iterator1 != path.end() && iterator2 != path2.end())
    {
        if (*iterator1 == *iterator2)
            pLast == *iterato1;
        iterator1++;
        iterator2++;
    }
    return pLast;
}
TreeNode* GetLastCommonParent(TreeNode* pRoot,TreeNode* pNode1,TreeNode* pNode2){
    if (pRoot == NULL || pNode1 == NULL || pNode2 == NULL)
        return NULL;
    list<TreeNode*>path1;
    GetNodePath(pRoot,pNode1,path1);
    list<TreeNode*>path2;
    GetNodePath(pRoot,pNode2,path2);
    return GetLastCommonNode(path1,path2);
}   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值