在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误

In this implementation of stack using linked list in C++, accessing struct headNode members count and top is giving run time error

本文关键字:count 成员 top headNode 运行时错误 结构体 访问 C++ 链表 实现 堆栈      更新时间:2023-10-16

我在使用链表实现堆栈时遇到问题。在c++中使用链表的堆栈实现中,方法createNode和push中的struct-headNode部分计数和top不可访问,并给出运行时错误。请告诉我为什么结构体headNode->top和headNode->count不可访问,或者如果您在这段代码中发现任何其他错误。

struct Node{
int data;
Node *next;
Node(int data):data(data), next(NULL){}
};
struct headNode{
int count{0};
Node *top ;
headNode():top(NULL){}
};
class Stack{
private:
headNode *head;
int c{0};
public:
Stack();
void createStack(int data);
void push(int data);
};
Stack::Stack():head(NULL){}
void Stack:: createStack(int data)
{
Node *topNode= new Node(data);
head->top=topNode; //RUNTIME ERROR IN THIS LINE OF CODE
head->count=c++; //RUNTIME ERROR IN THIS LINE OF CODE
}
void Stack:: push(int data)
{
if(head==NULL)
{
createStack(data);
}
else
{
Node *topNode= new Node(data);
topNode->next=head->top;
head->top=topNode;
head->count=c++;
}
}
int main()
{
Stack s ;
s.push(1);
}

当执行Stack s;时,构造函数会执行,但这一行:Stack::Stack():head(NULL)初始化head = NULL,然后在s.push(1);行中,函数push调用createStack(因为条件head == NULL为true(,这反过来会:

head->top=topNode;
head->count=c++;

但是head仍然是NULL,并且会产生您所经历的运行时错误。