我正在创建一个带有链接列表的堆栈。我编码了推送和显示堆栈部分,但是当我尝试显示堆栈内容时,它只是生成最后输入的数据作为输出。这是为什么发生?解释使用链接列表实现的堆栈的输出
struct LinkedStack {
int data;
struct LinkedStack* next;
};
struct LinkedStack *first = NULL;
struct LinkedStack *previous = NULL;
struct LinkedStack *current = NULL;
int main(void) {
int data = 0, choice = 0;
if(current == NULL) {
printf("\nNo Memory Allocated");
}
while(1) {
printf("\n1. Push Data");
printf("\n2. Pop Data");
printf("\n3. Display The Stack");
printf("\n4. Exit");
printf("\nEnter Your Choice::\n");
scanf("%d", &choice);
switch(choice) {
case 1:
current = (struct node *)malloc(sizeof(struct LinkedStack));
printf("Enter the data:: ");
scanf("%d", &data);
push(¤t, data);
break;
case 3:
printf("\n\n Stack Contents::");
displayStack(current);
break;
case 4:
exit(1);
default:
printf("\nWrong Choice.Enter Again");
}
}
}
void push(struct LinkedStack **s, int usrdata) {
if(first == NULL) {
first = *s;
}
if(previous != NULL) {
previous->next = *s;
}
(*s)->data = usrdata;;
(*s)->next = NULL;
previous = *s;
}
void displayStack(struct LinkedStack *s) {
struct LinkedStack *temp = (struct LinkedStack *)malloc(sizeof(struct LinkedStack));
if(temp == NULL) {
printf("No Memory Allocated");
}
temp = s;
while(temp != NULL) {
printf("\n %d", temp->data);
temp = temp->next;
}
}
再次阅读该问题。我已经在那里写了一切。它不可能比这更具体。 – arindrajit
在案例3中,displayStack(第一个)显示整个列表。如果你显示堆栈(当前),它将只显示最后一个项目。另外,你不需要在displayStack中使用malloc。在displayStack处: – cup
:不需要'malloc'。 – BLUEPIXY