【发布时间】:2017-02-12 14:45:47
【问题描述】:
尝试使用此程序将数据推送到堆栈时,我得到了错误的输出。即使堆栈大小为 5,打印堆栈元素也会进入无限循环,同时给出错误的值。错误是什么?
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *top = NULL;
int count = 0;
void push(int num) {
struct node *newNode = (struct node*)malloc(sizeof(int));
newNode->data = num;
newNode->next = NULL;
if (top == NULL) {
top = newNode;
} else {
struct node *temp = (struct node*)malloc(sizeof(int));
temp = top;
top = newNode;
top->next = temp;
free(temp);
}
count++;
}
int pop() {
if (top == NULL) {
printf("\nUnderflow- Stack is empty!");
return -1;
}
struct node *temp = (struct node*)malloc(sizeof(int));
temp = top;
top = top->next;
return temp->data;
}
int stackTop() {
if (top == NULL) {
printf("\nStack is empty");
return -1;
}
return top->data;
}
void printStack() {
if (top == NULL) {
printf("\nStack is empty. Nothing to print");
}
printf("\n");
while (top != NULL) {
printf("%d ", top->data);
top = top->next;
}
}
/* Count stack elements */
void stack_count() {
printf("\n No. of elements in stack : %d", count);
}
int main(void) {
int poppedValue, topValue;
push(1);
push(2);
push(3);
push(4);
push(5);
stack_count();
printStack();
poppedValue = pop();
topValue = stackTop();
printf("\nPop item : %d", poppedValue);
printf("\nTop Value: %d", topValue);
return 0;
}
输出:
No. of elements in stack : 5
5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 ....
【问题讨论】:
-
您在
push中有一个错误。阅读how to debug small programs如何找到它。 -
struct node* newNode = (struct node*)malloc(sizeof(int));-->struct node* newNode = malloc(sizeof(struct node)); -
struct node* temp = (struct node*)malloc(sizeof(int)); temp = top; top = newNode; top->next = temp; free(temp);-->newNode->next = top; top = newNode; -
@BLUEPIXY - 我真的认为应该将答案发布为作为答案,并且不难阅读格式化的 cmets。
-
printStack不应更改top。
标签: c data-structures stack