无法使用Stack的Pop()函数反转简单的字符串

问题描述 投票:0回答:1

我有一个简单的堆栈程序正在尝试反转字符串。我能够“显示”反转的字符串,但是当涉及存储Pop()函数返回的字符时,我却没有这样做。我下面的操作是在将字符串推入堆栈后的main()中,尝试使用重用str[]存储反向字符串。由于它是一个数组,因此我应该能够对其进行修改。但是,当我这样做时,出于某种奇怪的原因,for循环只运行一次。我猜它正在这样做,因为在第二次迭代的pop() *head = NULL中因此失败。

我无法多次运行for循环。我的问题是是什么阻止了我存储反向字符串?

1)为什么在使用str [i]时for循环仅运行一次?

2)我是否以某种奇怪的方式使用str [i]导致这种情况发生?

char ret = '\0';
void Push(Node **head, char data)
{
    Node *temp = (Node*)malloc(sizeof(Node));
    temp->data = data;
    temp->next = NULL;
    if (*head == NULL)
    {
        *head = temp;
        return;
    }

    temp->next = *head;
    *head = temp;
    return;
}

void PrintAll(Node *temp)
{
    if(temp == NULL) return;
    printf("%c, ", temp->data);
    PrintAll(temp->next);
}
char Pop(Node **head)
{
    if(*head == NULL)  
    {
        return '\0';
    }
    Node *temp = *head;
    ret = temp->data;
    *head = (*head)->next;
    free (temp);
    return ret;
}

int main()
{
    Node *head = NULL;

    char str[] = "helloworld";
    printf("Original String is:%s\n", str);
    printf("Length is:%lu\n", strlen(str));

    for (int i = 0; i <=strlen(str); i++)
    {
        Push(&head, str[i]);
    }

    printf ("String has been pushed to the stack.\n");
    PrintAll(head);
    printf("\nString has been printed. Now popping:%ld.\n", strlen(str));


    //Problem starts here in this for-loop
    for (int i = 0; i <=strlen(str); i++)
    {
        str[i] = Pop(&head); //When these next lines are enabled, the for-loop runs only once!
        printf("%c, ", str[i]); //Pop() is returning the value from a global variable 'ret'
        //printf("%c ", Pop(&head)); //if two previous lines are disabled, string is displayed in reverse

    }
    printf("\n");
    printf ("String has been popped from the stack.\n");
    return 0;
}
c stack reverse
1个回答
0
投票

您压入堆栈的最后一件事是字符串的空终止符。因此,您弹出的第一件事就是这个空终止符。分配str[i] = Pop(&head);时,将第一个字符设为空终止符。结果,strlen(str)现在为0,并且由于1 <= 0不正确,因此循环在下一次迭代时停止。

您不应该将空终止符压入堆栈。第一个循环应使用i < strlen(str)而不是i <= strlen(str)(更有效的方法是str[i] != 0)。

并且在弹出时,您不应该使用结果字符串的strlen(),因为您尚不知道它将持续多长时间。您应该调用Pop(&head)直到返回'\0',这表明您已清空堆栈。

int main()
{
    Node *head = NULL;

    char str[] = "helloworld";
    printf("Original String is:%s\n", str);
    printf("Length is:%lu\n", strlen(str));

    for (int i = 0; str[i] != 0; i++)
    {
        Push(&head, str[i]);
    }

    printf ("String has been pushed to the stack.\n");
    PrintAll(head);
    printf("\nString has been printed. Now popping:%ld.\n", strlen(str));

    for (int i = 0; str[i] = Pop(&head); i++)
    {
        printf("%c, ", str[i]); //Pop() is returning the value from a global variable 'ret'
    }
    printf("\n");
    printf ("String has been popped from the stack.\n");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.