问题:用O(n)的算法把"www.taobao.com"转成"com.taobao.www"
方法:
用两个栈
从左至右扫描字符串,以点号为分隔符,每次扫描到点号的时候就把前面的字符压栈到s1,
然后再一直吧s1里的东西弹栈到s2,一直弹到s1空为止
中间过程中弄几个标记变量保存数组指针,
最后把s2里的东西从栈顶一直弹出来输出直到s2为空就可以了
代码如下:
#include<iostream>
#include<cstring>
#define SIZE 20
using namespace std;
class Stack
{
private:
char stack[SIZE];
int top;
public:
Stack()
{
top=-1;
}
~Stack()
{
}
void push(char x)
{
top++;
stack[top] = x;
}
char pop()
{
return stack[top--];
}
bool isempty()
{ if(top==-1)
return true;
else
return false;
}
bool isfull()
{
if(top==SIZE)
return true;
else
return false;
}
};
int main()
{
char str[] = "www.taobao.com";
int i,j;
Stack s1;
Stack s2;
int temp;
int flag = 0;
for(i = 0 ;i <= strlen(str);i++)
{
if(str[i]=='.'||str[i]=='\0')
{
temp = i;
for(j = flag; j<temp ;j++ )
{
s1.push(str[j]);
}
while(!s1.isempty())
{
s2.push(s1.pop());
}
flag = temp + 1;
s2.push('.');
}
}
s2.pop();
while(!s2.isempty())
{
cout<<s2.pop();
}
cout<<endl;
}