day06使用两个栈实现一个队列+使用两个队列实现一个栈+字符串空格替换

来源:互联网 发布:tp wifi访客网络 编辑:程序博客网 时间:2024/06/05 15:38
  • 1.使用两个栈实现一个队列
class Queue{public:    void Push(int val)    {        s1.push(val);    }    void Pop()    {        assert(s1.size() || s2.size());        if(s2.empty())        {            while(!s1.empty())            {                int temp = s1.top();                s2.push(temp);                s1.pop();            }        }        s2.pop();    }    int Front()    {        assert(s1.size() || s2.size());        if(s2.empty())        {            while(!s1.empty())            {                int temp = s1.top();                s2.push(temp);                s1.pop();            }        }        return s2.top();    }private:    stack<int> s1;    stack<int> s2;};
  • 使用两个队列实现一个栈
class Stack{public:    void Push(int val)    {        q1.push(val);    }    void Pop()    {        assert(q1.size()); //一定要有元素才能出栈操作。        while(q1.size() != 1)        {            q2.push( q1.front() );            q1.pop();        }        q1.pop();        swap(q1, q2); //交换队列,q2就是一个辅助队列,     }    int  Top()    {        assert(q1.size());        return  q1.back();    }private:    queue<int> q1;    queue<int> q2;};
  • 替换字符串中的空格为$$$。要求时间复杂度为O(N)
例如:将"talk is cheap show me the code"替换。为"talk$$$is$$$cheap$$$show$$$me$$$the$$$code"
void ReplaceSpace(char *str){    assert(str);    char *pcur = str;    int spacenum = 0;    while(*pcur != '\0')    {        if( isspace(*pcur) )        {            spacenum++;        }        pcur++;    }    char *ptail = str+strlen(str);    char *pnewtail = ptail+2*spacenum;    while(ptail != pnewtail)    {        *pnewtail = *ptail;        if( isspace(*pnewtail) )        {            *pnewtail-- = '$';            *pnewtail-- = '$';            *pnewtail-- = '$';            ptail--;        }        else        {            pnewtail--;            ptail--;        }    }}