剑指offer——面试案例

来源:互联网 发布:radeon pro 580windows 编辑:程序博客网 时间:2024/05/18 15:57

剑指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);}   
原创粉丝点击