我的代码
#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/