简体   繁体   English

使用堆栈反转字符串

[英]Reversing string using stack

I have a problem with reversing string using stack structure. 我在使用堆栈结构反转字符串时遇到问题。

I made some code to reverse 'apple' to 'elppa' and seems like it worked well... 我编写了一些代码来将“ apple”反转为“ elppa”,似乎运行良好……

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_STACK_SIZE 5

typedef int element;

element stack[MAX_STACK_SIZE];

int top = -1;

void initialize() {
    top = -1;
}

int isEmpty() {
    return (top == -1);
}

int isFull() {
    return (top == (MAX_STACK_SIZE - 1));
}

void push(element item) {
    if (isFull()) {
        printf("stack is full, cannot add element.\n");
    }
    else{
        stack[++top] = item;
    }
}

element pop() {
    if (isEmpty()) {
        printf("stack is empty\n");
    }
    else {
        return stack[top--];
    }
}

char* reverse(char* s) {
    const int len = sizeof(s) + 1;
    char* rstring = new char[len];
    initialize();
    for (int i = 0; i < len; i++) {
        push(s[i]);
    }
    int tmp = 0;
    while(isEmpty()==false){
        rstring[tmp++]=pop();
    }
    for (int i = 0; i < len; i++) {
        printf("%c\n", rstring[i]);
    }
    return rstring;
}

void main() {
    char* str1 = "apple";
    char* str2 = reverse(str1);

    printf("before : %s \n", str1);
    printf("after : %s \n", str2);
    getchar();
}

the result is here I got the answer(elppa) but it also printed out some other characters what I wasn`t intended. 结果是在这里我得到了答案(elppa),但它也打印出了我原本不想要的其他字符。 Why I got this thing? 为什么我得到这个东西? It may something to do with memory array or something but do not know exactly what was happened memory. 这可能与内存阵列有关,或者某些原因却并不确切知道发生了什么事情。 How to fix the problem? 如何解决问题?

You haven't taken into account the string termination character '\\0' . 您尚未考虑字符串终止符'\\0' You are printing the sting using %s with printf. 您正在将%s与printf一起使用。

Once rstring has been calculated after unwinding the stack, you should append '\\0' to rstring. 展开堆栈后,一旦计算出rstring,则应在rstring后面附加'\\0' Hopefully this will solve your problem. 希望这可以解决您的问题。

By using sizeof you will get the data_type size (in this case, size of char*) in bytes. 通过使用sizeof您将获得以字节为单位的data_type大小(在这种情况下,为char *的大小)。 You should use strlen instead. 您应该改用strlen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM