Vote count:
0
i was trying to perform stack functions using nested structures. But i am facing problem initializing the stack.
its the problem with the initialize function of LinkList structure in the code given below.
Please help and let me know what can i do to run this code completely.
thanks in advance
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;
}
asked 1 min ago
How to initialize nested structures in C++
Aucun commentaire:
Enregistrer un commentaire