您的位置:首页 > 其它

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

2017-07-18 23:41 417 查看
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--;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐