剑指Offer-- 两个栈模拟队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
看代码:
#include<iostream>
#include<stack>
using namespace std;
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int t = stack2.top();
stack2.pop();
return t;
}
int front(){
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
return stack2.top();
}
bool empty(){
if(stack1.empty() && stack2.empty()){
return true;
}
return false;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main(){
Solution S;
// stack<int> s ;
// s.push(1);
// s.push(2);
// s.push(3);
// while(!s.empty()){
// int n = s.top();
// cout<<n<<endl;
// s.pop();
// }
S.push(1);
S.push(3);
S.push(3);
S.push(0);
S.push(-1);
while(!S.empty()){
int n = S.front();
cout<<n<<endl;
S.pop();
}
return 0;
}
替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
不多说Java 实现 如果C实现 遍历字符串 if(str==“ ”)else{ s ="%20“”;}
代码:
public class replaceChar {
public String replaceSpace(StringBuffer str) {
String source = str.toString();
source = source.replaceAll(" ", "%20");
return source;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer str = new StringBuffer("We are happy");
String ans = new replaceChar().replaceSpace(str);
System.out.println(ans);
}
}