c++ - 打印堆栈的元素

标签 c++ linked-list stack

我的代码

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

struct node {
    char ch;
    struct node *next;
};
struct node *first,*top1,*newptr;

void push_back(char data) { //Pushes data into the stack
    if (first == NULL) {
        first = new node();
        first->next = NULL;
        first->ch = data;
    }

    else {
        first = new node();
        top1->next = first;
        top1->ch = data;
        first = top1;
    }
}

void display() {
    top1 = first;

    if (top1 == NULL){
        printf("Stack is empty");
        return;
    }

    while (top1 != NULL){
        printf("%c ", top1->ch);
        top1 = top1->next;
    }
}


main() {
    first = NULL;
    char EXP[100];

    scanf("%s",&EXP);
    system("cls");
    int len = strlen(EXP);

    for(int i=0;i<len;i++)
        push_back(EXP[i]);

    display();

    system("pause");
}

我的程序应该为用户获取一个字符串,然后将每个字符放入一个堆栈中,然后我会打印回该字符串。当我运行我的代码时,它只能显示第一个字符。我错过了什么吗?

最佳答案

当你第二次 push_back() 时,你会立即覆盖 first

else {
    first = new node();    //oops
    top1->next = first;
    top1->ch = data;
    first = top1;

丢失它之前指向的数据。

关于c++ - 打印堆栈的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706357/

相关文章:

c++ - iostream是否占用堆栈空间?

algorithm - 一起实现堆栈和队列的最有效方法?

c++ - 为类模板重载非成员算法

c++ - 带有 5 个参数的 WPARAM

java - 是否有 Java LinkedList 方法可用作环表?

c - 为什么当我写到数组末尾时我的程序没有崩溃?

c++ - 在 C++ 运行时从指针访问对象实例

C++ Autotools Google 测试框架

c++程序崩溃链表?

c++ - 删除双向链表中的功能故障