Define and implement a stack that contains doubles. The outline the class is: cl
ID: 3528136 • Letter: D
Question
Define and implement a stack that contains doubles. The outline the class is: class DoubleStack{ public: DoubleStack(int capacity); void push(double x); double pop( ); double peek( ) int size( ); bool isFull( ); private: int top; double *data; };Explanation / Answer
void push(int item, struct node **tp) { struct node *p; p=(struct node *)malloc(sizeof(struct node)); p->info=item; p->next=*tp; *tp=p; // wrong change it to tp=&p; } tp is a pointer pointer . Ok. means it will be keeping address of a pointer tp will be keeping address of last element pushed in to stack .ie. top element. when a new element pushed in to stack , current top becomes next to top. and current becomes top initially when push () is call top is 1st element in the stack. p->next=*tp; // this means top becomes next to current,ie top is now 2nd item of the stack tp=&p; // setting current node as top of the statck. ie, 1st so when you call this function what you have to pass is the value to be pushed and , the address of first element or not in the stack value is in variable item Address of top node is in tp. so the function call will look like push(item,tp) since DNA of push is push(int, struct node ** ) if you want to pass &top , you might need push(int, struct node *** ) second think is in struct node{ int info; struct node *link; // you specified variable name as link }; in the push () you are using variable "next" . change it to "link" another problem you will face is top will always be NULL. because when you pass top , like this push(item,tp) its still call by value. not reference.so make top global or make declaration of top in main function like this struct node * top. then call push(item,&top). here is the working code #include #include struct node{ int info; struct node *link; } ; void push(int item, struct node **tp) { struct node *p; p=(struct node *) malloc(sizeof(struct node)); p->info=item; p->link=*tp; *tp = p ;//tp=&p; //printf("%d", (*tp)->info); //if(p->link !=NULL) //printf("%d", (p->link)->info ); } int main() { struct node *top = NULL ; // push(30,&top); push(40,&top); push(50,&top); while(top !=NULL) { printf("%d", top->info); top = top->link; } return 0; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.