首页 > 解决方案 > 使用链表中的堆栈反转C中的字符串

问题描述

我正在尝试使用堆栈反转给定的字符串。我正在使用链表,因为与数组相比,它占用的内存更少。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 100

struct Stack{
    char ele;
    struct Stack *next;
};

struct Stack* next_node(char element){
    struct Stack *node=(struct Stack *)malloc(sizeof(struct Stack));
    node->ele=element;
    node->next=NULL;
    return node;
}

int isEmpty(struct Stack *node){
    return node==NULL;
}

void push(struct Stack **node, char element){
    struct Stack *temp=next_node(element);
    temp->next=*node;
    *node=temp;
}

char pop(struct Stack **node){
    if(isEmpty(*node)){
        return 'a';
    }
    struct Stack *temp=*node;
    *node=(*node)->next;
    free(temp);
}

void rev(char str[]){
    int i;
    int n=strlen(str);
    struct Stack *s=(struct Stack *)malloc(sizeof(struct Stack));
    for(i=0;i<n;i++)
        push(&s, str[i]);
    for(i=0;i<n;i++)
        str[i]=pop(&s);
    printf("The reversed string is: %s\n", str);
}

int main()
{
    char string[M], op[1];
    do{
        printf("Enter the string to be reversed: ");
        scanf("%s", string);
        rev(string);
        printf("Do you want to go again?(Y/N): ");
        scanf("%s", op);
    }while(op[0]=='Y');
}

但是,我没有得到任何输出,它只是说,“反转的字符串是:”

我通过替换尝试了稍微不同的代码

node->ele=element;

strcpy(node->ele, element);

但这给了我一个警告,上面写着:

warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast

我无法理解为什么会发生这样的事情。任何帮助表示赞赏!:-)

标签: clinked-liststack

解决方案


你可以完全跳过堆栈,做一些更简单、更快的事情,如下所示:

void rev(char str[])
{
    int i;
    int n = strlen(str);
    
    for(i=0; i<n/2; i++) {
        char tempChar = str[i];
        str[i] = str[n-i-1];
        str[n-i-1] = tempChar;
    }
    printf("The reversed string is: %s\n", str);
}

基本上,只需遍历字符串的一半(如果长度为奇数,则不包括中间字符),并从字符串的左半部分和右半部分交换字符。


推荐阅读