在C中使用链接列表实现堆栈 [英] implementing stack with linked list in C
问题描述
我在使用带有struct的链表实现Stack时遇到麻烦.该程序编译良好,但是当我运行它时,它会打印第一个元素,但随后将下一个节点读取为NULL.我认为将堆栈传递给push方法可能是错误的,但是我不确定,并且修复失败,因此我寻求您的帮助:
I'm having trouble implementing a Stack using a linked list with struct. The program compiles fine but when I run it, it prints the first element but then reads the next node as a NULL. I think it might be an error with my passing of the stack to the push method but I am not sure and I have not been successful in fixing it so I'm asking for your help:
#include <stdio.h>
#include <stdlib.h>
struct stackNode{
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
void convertToPostfix(char infix[], char postfix[]);
int isOperator(char c);
int precedence(char operator1, char operator2);
void push(StackNodePtr *topPtr, char value);
char pop(StackNodePtr *topPtr);
char stackTop(StackNodePtr topPtr);
int isEmpty(StackNodePtr topPtr);
void printStack(StackNodePtr topPtr);
int main(){
convertToPostfix(NULL, NULL);
return 0;
}
void convertToPostfix(char infix[], char postfix[]){
StackNode stack = {'(', NULL};
StackNodePtr stackPtr = &stack;
push(stackPtr, 'a');
//printf("%s\n", stackPtr->data);
printStack(&stack);
}
void push(StackNodePtr *topPtr, char value){
StackNode *node;
node=(StackNodePtr)malloc(sizeof(StackNodePtr));
node->data=value;
node->nextPtr=*topPtr;
*topPtr=node;
}
void printStack(StackNodePtr topPtr){
if(topPtr == NULL){
printf("%s\n", "NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
return;
}
printf("%c\n", topPtr->data);
printStack(topPtr->nextPtr);
}
任何帮助将不胜感激.
谢谢
推荐答案
我可以看到几个问题:
1)当您将stackPtr
的地址传递给push函数时,printStack(&stack);
应该为printStack(stackPtr);
.
1) printStack(&stack);
should be printStack(stackPtr);
as you are passing address of stackPtr
to the push function.
2)
node = (StackNodePtr)malloc(sizeof(StackNodePtr));
应为:
node = malloc(sizeof(StackNode));
3)
push(stackPtr, 'a');
应为:
push(&stackPtr, 'a');
您需要传递顶部指针的地址.
As you need to pass the address of the top pointer.
这篇关于在C中使用链接列表实现堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!