利用栈实现输入字符串的逆序输出
时间: 2023-10-11 13:07:12 浏览: 60
可以使用一个栈来实现输入字符串的逆序输出。具体方法如下:
1. 遍历输入字符串,依次将每个字符压入栈中;
2. 弹出栈中的字符,依次输出,即可得到输入字符串的逆序输出。
下面是 Python 代码实现:
```python
def reverse_string(s):
stack = []
for c in s:
stack.append(c)
res = ''
while stack:
res += stack.pop()
return res
```
示例:
```python
s = 'hello world'
print(reverse_string(s)) # 输出:dlrow olleh
```
相关问题
利用栈实现字符串的逆序c语言
代码是什么?
下面是一份利用栈实现字符串逆序的 C 语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
// 定义 Stack 结构体
typedef struct {
char data[MAX_LEN];
int top;
} Stack;
// 初始化栈
void init(Stack *stack) {
stack->top = -1;
}
// 入栈
void push(Stack *stack, char ch) {
if (stack->top == MAX_LEN - 1) {
printf("Stack overflow\n");
exit(1);
}
stack->data[++stack->top] = ch;
}
// 出栈
char pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return stack->data[stack->top--];
}
// 字符串逆序
void reverse(char *str) {
Stack stack;
init(&stack);
// 将字符串中每个字符入栈
for (int i = 0; i < strlen(str); i++) {
push(&stack, str[i]);
}
// 出栈并输出字符,即可得到逆序字符串
for (int i = 0; i < strlen(str); i++) {
str[i] = pop(&stack);
}
}
int main() {
char str[MAX_LEN];
printf("请输入一个字符串:\n");
scanf("%s", str);
reverse(str);
printf("逆序后的字符串:%s\n", str);
return 0;
}
```
注意,此代码可能不是最优雅的实现方式,但它可以帮助你理解如何利用栈实现字符串逆序的思路。
利用栈的算法,质因数分解逆序输出C++
下面是Python的实现代码:
```python
def prime_factors(n):
stack = []
i = 2
while i * i <= n:
while n % i == 0:
stack.append(i)
n //= i
i += 1
if n > 1:
stack.append(n)
res = ""
while stack:
res += str(stack.pop()) + " "
return res.strip()
n = int(input("请输入一个正整数:"))
print(prime_factors(n))
```
解释一下算法思路:
首先定义一个栈,用于保存质因子。从2开始,不断尝试除以自然数,如果能整除,则将自然数i作为一个质因子压入栈中,同时将原数除以i。如果不能整除,则i加1继续尝试。
当i * i大于原数时,表示已经找到了所有的质因子。如果原数剩下的值大于1,说明剩下的这个数也是质因子之一,也需要压入栈中。
最后将栈中的质因子弹出,利用字符串拼接的方式逆序输出即可。