Ich bekomme eine falsche Ausgabe, während ich versuche, Daten im Stack mit diesem Programm zu übertragen. Obwohl die Stapelgröße 5 ist, wird beim Drucken der Stapelelemente eine Endlosschleife ausgeführt, während falsche Werte angegeben werden. Was ist der Fehler?Fehler beim Implementieren des Stacks mit der Linkedlist in C
#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;
}
Ausgang:
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 ....
Sie haben einen Fehler in 'push'. Lesen Sie weiter, wie [kleine Programme zu debuggen] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) finden Sie es. – StoryTeller
'struct Knoten * newNode = (struct Knoten *) malloc (sizeof (int));' -> 'struct Knoten * newNode = malloc (sizeof (struct Knoten));' – BLUEPIXY
'struct Knoten * temp = (struct Knoten *) malloc (Größe von (int)); Temp = oben; top = neuer Knoten; top-> nächste = temp; frei (temp); '->' newNode-> next = top; top = newNode; ' – BLUEPIXY