使用用户定义函数的字符串反转

String Reverse using user defined functions

本文关键字:字符串 函数 用户 定义      更新时间:2023-10-16

我试图使用堆栈反转字符串,但问题是我自己定义函数,而不使用库。这是代码:

const int size = 50;
int top = -1;
char C[size];
int i = 0;
void push(int x){
top++;
if (top > size)
cout << "Error: Stackoverflow" << endl;
else
C[top] = x;
}
bool isEmpty() {
if (top < 0)
return true;
else
return false;
}
bool isFull() {
if (top > size)
return true;
else
return false;
}
void pop() {
if (isEmpty())
cout << "Error: The stack is empty!" << endl;
else
top--;
}
int Top() {
return C[top];
}
void Reverse(char *C, int n) {
// For Push
for (i = 0; i < n; i++)
push(C[i]);
// For pop
for(i = 0; i < n; i++) {
C[i] = Top();
pop();
}
}
int main() {
cout << "Enter the string: ";
cin >> C;
Reverse(C, strlen(C));
cout << "The reversed string is: " << C;
return 0;
}

现在,根据代码,字符串应该被反转,但我得到了以下输出:

Enter the string: Hi
The reversed string is: ii

我很确定push((做得很好,但我想pop((有问题吗?

字符串和堆栈都使用相同的数组,因此在C[i] = Top();中,您将替换最后一个字符中的第一个字符,从而丢失它。

#include <iostream>
#include <string.h>
using namespace std;
const int size = 50;
int top = -1;
char C[size];
char stack[size];
int i = 0;
void push(int x)
{
top++;
if (top > size)
{
cout << "Error: Stackoverflow" << endl;
}
else
{
stack[top] = x;
}
}
bool isEmpty()
{
if (top < 0)
{
return true;
}
else
{
return false;
}
}
bool isFull()
{
if (top > size)
{
return true;
}
else
{
return false;
}
}
void pop()
{
if (isEmpty())
{
cout << "Error: The stack is empty!" << endl;
}
else
{
top--;
}
}
int Top()
{
return stack[top];
}
void Reverse(char *C, int n)
{
// For Push
for (i = 0; i < n; i++)
{
push(C[i]);
}
// For pop
for (i = 0; i < n; i++)
{
C[i] = Top();
pop();
}
}
int main()
{
cout << "Enter the string: ";
cin >> C;
Reverse(C, strlen(C));
cout << "The reversed string is: " << C;
return 0;
}