我试图使用嵌套结构来执行堆栈函数。 但我面临初始化堆栈的问题。如何在C++中初始化嵌套结构
其在下面给出的代码中的LinkList结构的初始化函数的问题。
请帮助,让我知道我能做些什么来完全运行此代码。
在此先感谢
CODE:
#include<iostream>
using namespace std;
class stack{
struct ch;
ch * ptr;
public:
void initialize();
void push(int *);
int* pop();
int* peek();
};
struct stack::ch{
struct LinkList{
int * data;
LinkList * next;
void initialize(int* dat, ch* nxt);
}*head;
};
/*this is where i am facing problem*/
void stack::ch::LinkList::initialize(int *dat, ch *nxt){
data = dat;
if(nxt->head) //as i cannot access head of nxt,so code is crashing
next = nxt->head;
else
next = 0;
}
void stack::initialize()
{
ptr = 0;
}
void stack::push(int *dat)
{
ch::LinkList* newNode = new ch::LinkList;
newNode->initialize(dat,ptr);
ptr->head = newNode;
}
int* stack::pop()
{
if(ptr == 0)
return 0;
ch::LinkList* oldHead = ptr->head;
ptr->head = ptr->head->next;
int * dat = oldHead->data;
delete oldHead;
return dat;
}
int* stack::peek()
{
if(ptr->head == 0)
return 0;
return ptr->head->data;
}
int main()
{
stack obj;
obj.initialize();
int a = 10;
int b = 11;
int c = 12;
int d = 13;
obj.push(&a);
obj.push(&b);
obj.push(&c);
obj.push(&d);
int *f;
while((f = obj.pop())!=0)
{
cout<<*(obj.peek())<<endl;
//obj.pop();
}
return 0;
}
你调试了吗?你应该得到一个编译器诊断哪里出了问题?这应该是最容易找出问题的方法。 – DumbCoder 2015-03-02 10:13:40
“我正面临问题”对于告诉我们这是什么问题并没有多大作用,是吗? – 2015-03-02 11:06:02
是的,我现在ptr是空的,这是如果(Nxt->头)无法访问和代码崩溃。 – 2015-03-02 11:57:52