使用堆栈反转字符串

时间:2021-05-25 14:03:59

标签: java c++ string stack

我已经尝试了很长一段时间,但仍然无法.. 根据我们需要做的所有问题,id 在不做任何其他更改的情况下完成功能.. 我们允许完全重写代码弹出和显示弹出的值可能有效,但没有。

问题-

Given a string, the task is to reverse the string using stack data structure.

Complete the function reverseString() that accepts the string, and reverses the string.

输入类型-

The first line of input will contains an integer T denoting the no of test cases. Then T test cases follow. 
Each test case contains a number N.
Then N strings follow which are to be reversed

图片上的代码 -

/* class CQStack{
      public CQStack(int s) // constructor
      public void push(int j) // put item on top of stack
      public int pop() // take item from top of stack
      public boolean isEmpty() // true if stack is empty
      public boolean isFull() // true if stack is full
    }
    CQStack class already defined as per the above blueprint
*/

static String reverseString(CQStack s, String st)
{

}

enter image description here

样本输入

1 // No. of test cases
2 // No. of strings
CodeQuotient
Code
Sample Output

输出-

tneitouQedoC
edoC

1 个答案:

答案 0 :(得分:1)

堆栈以后进/先出的方式运行。因此,如果您将字符串中的所有字符(按顺序)推送,然后将它们弹出,您将按顺序弹出它们。

我更喜欢迭代字符串中的字符的方式是:

for (const char c: str) {
}

你可以像这样构建一个字符串:

str = str + c;

不过,我不会真正编写您的代码。