这是源代码:
#include <stdio.h>
#include <stdlib.h>
struct Fraction{
int num;
int denom;
};
typedef struct Fraction Frac;
typedef Frac* FracPtr;
struct FracNode {
Frac fr;
struct FracNode* next;
};
typedef struct FracNode FrNode;
typedef FrNode* FrNodePtr;
struct FracStack {
int stkSize;
FrNodePtr frNodePtr;
};
typedef struct FracStack FrStk;
typedef FrStk* FrStkPtr;
FrNodePtr createFrNode(void);
FrStkPtr createFrNodeStk(void);
void pushFrNode(FrStkPtr*, FrNodePtr);
void printStack(FrStkPtr);
int main() {
FrNodePtr frNodeTmpPtr = 0;
FrNodePtr frNodeTmpPtr2 = 0;
FrStkPtr frStkPtr = 0;
frNodeTmpPtr = createFrNode();
frStkPtr = createFrNodeStk();
pushFrNode(&frStkPtr, frNodeTmpPtr);
printStack(frStkPtr);
frNodeTmpPtr2 = createFrNode();
pushFrNode(&frStkPtr, frNodeTmpPtr2);
printStack(frStkPtr); // Only the newly created fraction is printed. frNodeTmpPtr didn't get printed as part of the stack. Is there an issue with my print function or the push function?
free (frNodeTmpPtr);
free (frNodeTmpPtr2);
free (frStkPtr);
return 0;
}
//Print Stack
void printStack(FrStkPtr stkPtr) {
while (stkPtr->frNodePtr != 0) {
printf("Numerator: %d & Denominator: %d\n\n", stkPtr->frNodePtr->fr.num, stkPtr->frNodePtr->fr.denom);
stkPtr->frNodePtr = stkPtr->frNodePtr->next;
}
return;
}
//Push Node
void pushFrNode(FrStkPtr* stkPtr, FrNodePtr nPtr) {
if ((*stkPtr)->frNodePtr != 0) {
nPtr->next = ((*stkPtr))->frNodePtr;
}
(*stkPtr)->frNodePtr = nPtr;
(*stkPtr)->stkSize++;
return;
}
//Create Stack
FrStkPtr createFrNodeStk() {
FrStkPtr frStkPtr;
frStkPtr = (FrStkPtr) malloc (sizeof(FrStk));
frStkPtr->stkSize = 0;
frStkPtr->frNodePtr = 0;
return frStkPtr;
}
//Create Node
FrNodePtr createFrNode() {
FrNodePtr frNodePtr;
frNodePtr = (FrNodePtr) malloc (sizeof(FrNode));
frNodePtr->next = 0;
printf("Enter the numerator: ");
scanf("%d", &(frNodePtr->fr.num));
do {
printf("\nEnter a non-zero denominator: ");
scanf("%d", &(frNodePtr->fr.denom));
if (frNodePtr->fr.denom < 0) {
frNodePtr->fr.denom = -(frNodePtr->fr.denom);
frNodePtr->fr.num = -(frNodePtr->fr.num);
}
} while (frNodePtr->fr.denom == 0);
return frNodePtr;
}
在main中,我创建了一个分数,将其推入创建的堆栈中。打印出来。然后,我创建了另一个分数,将其推入堆栈并打印出来。问题是当我打印出堆栈时,它只打印出最后创建的分数,而不是两个分数。
示例运行:
输入分子:1
输入非零分母:1
分子:1&amp;分母:1
输入分子:2
输入非零分母:2
分子:2&amp;分母:2 //我希望这部分打印出1/1和2/2而不仅仅是2/2
答案 0 :(得分:0)
将打印功能更改为以下内容:
//Print Stack
void printStack(FrStkPtr stkPtr) {
FrNodePtr pointer = stkPtr->frNodePtr;
while (pointer != 0) {
printf("Numerator: %d & Denominator: %d\n\n", pointer->fr.num, pointer->fr.denom);
pointer = pointer->next;
}
return;
}