如何在C ++中初始化嵌套结构

时间:2015-03-02 09:58:12

标签: c++ nested structure

我试图使用嵌套结构执行堆栈功能。 但我正面临着初始化堆栈的问题。

下面给出的代码中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;
}

1 个答案:

答案 0 :(得分:0)

您应该自己调试代码。

void stack::push(int *dat)
{
    ch::LinkList* newNode = new ch::LinkList;
    newNode->initialize(dat,ptr);
    ptr->head = newNode;    
}

void stack::ch::LinkList::initialize(int *dat, ch *nxt){
    data = dat;
    if(nxt->head)    
        next = nxt->head;
    else
        next = 0;
}

请注意:ptrnullptr,因此nxt也是nullptr。 所以你崩溃了...
使ptr不为空,并修复你的pop函数错误,这没问题。