一、要求实现三个功能,调用“edit ”进行数据录入,调用“rollback”进行撤销,必须录入之后方可撤销,否则输出E,调用“restore”进行撤销恢复
同时,必须在撤销之后才可以进行恢复。
输入第一行为一共的操作次数,接下来的N行,每行代表一个命令,输出为N行,为每一步操作之后的显示结果。
输入:7,rollback,edit 1,edit 2,edit 3,restore,rollback,restore
输出:E,1,2,E,3,2,3
void Print(vector<int> &ve,int n)
{
stack<int> st_push;
stack<int> st_rash;
for(int i = 0; i < n*2; i += 2)
{
if(ve[i] == 0)
{
st_push.push(ve[i+1]);
cout<<ve[i+1]<<endl;
}
else if(ve[i] == 1)
{
if(st_push.empty())
{
cout<<"E"<<endl;
}
else
{
int tmp = st_push.top();
st_push.pop();
st_rash.push(tmp);
cout<<st_push.top()<<endl;
}
}
else
{
if(st_rash.empty())
{
cout<<"E"<<endl;
}
else
{
int tmp = st_rash.top();
st_rash.pop();
st_push.push(tmp);
cout<<tmp<<endl;
}
}
}
}
void main()
{
string s;
int n;
cin>>n;
vector<int> ve;
getchar();//不可省
for(int i = 0; i < n; ++i)
{
getline(cin,s);
if(strncmp(s.c_str(),"edit",4) == 0)
{
ve.push_back(0);
ve.push_back(s[s.size() - 1] - '0');
}
else if(strncmp(s.c_str(),"rollback",8) == 0)
{
ve.push_back(1);
ve.push_back(1);
}
else if(strncmp(s.c_str(),"restore",7) == 0)
{
ve.push_back(2);
ve.push_back(2);
}
}
Print(ve,n);
}
二、统计二叉树中每一行的节点的个数,定义结构体如下:
struct InviteNode
{
int user_id;
InviteNode *children[10];
};
构建一棵树太复杂了,就只写出,判断的代码吧,欢迎指教。
struct InviteNode
{
int user_id;
InviteNode *children[10];
};
void Print_invite_levels(InviteNode *root)
{
int num = 0;
queue<InviteNode *> qu;
qu.push(root);
while(!qu.empty())
{
int size = qu.size();
for(int i = 0; i < size; ++i)
{
InviteNode* tmp = qu.front();
qu.pop();
for(int i = 0; i < 10; ++i)
{
if(tmp->children[i] != NULL)
{
num++;
qu.push(tmp->children[i]);
}
}
}
cout<<num<<endl;
num = 0;
}
}
三、输入一个数字,输出从0到该数字的字典序排序
例如,输入102,输出0,1,10,100,101,102,11,12......19,2,20,21....99
int Get_len(int number)
{
int num = 0;
while(number != 0)
{
num++;
number /= 10;
}
return num;
}
char *Get_string1(int num,char *str)
{
if(num == 0)
{
str[0] = '0';
str[1] = '\0';
}
else
{
int n = Get_len(num);
str[n] = '\0';
while(num)
{
char ch = num % 10 + '0';
str[--n] = ch;
num /= 10;
}
}
return str;
}
void main()
{
int number;
cin>>number;
int n = Get_len(number);
char **ar = new char*[number + 1];
for(int i = 0; i <= number; ++i)
{
ar[i] = new char[n + 1];
if(ar[i] == NULL)
{
while(--i >= 0)
{
delete []ar[i];
}
break;
}
}
for(int i = 0; i <= number; ++i)
{
ar[i] = Get_string1(i,ar[i]);
}
for(int i = 0; i <= number; ++i)
{
for(int j = i+1; j <= number; ++j)
{
if(strcmp(ar[i],ar[j]) > 0)
{
char *tmp = ar[i];
ar[i] = ar[j];
ar[j ] = tmp;
}
}
}
for(int i = 0; i <= number; ++i)
{
cout<<ar[i]<<endl;
}
}
这个方法,空间复杂度有些太大了,而且时间复杂度也不低,欢迎指教更好的方法。