Create a program that uses a derived class based on the list class you’ve create
ID: 2246767 • Letter: C
Question
Create a program that uses a derived class based on the list class you’ve created in the first program. This program will use a stack data type.
class node {
void *info;
node *next;
public:
node (void *v) {info = v; next = 0; }
void put_next (node *n) {next = n;}
node *get_next ( ) {return next;}
void *get_info ( ) {return info;}
};
class list {
node *head;
int node_num;
public:
list ( ) { node_num = 0; head = 0;}
Write functions to push and pop the stack. Write a driver main program which gives 5 values (5 nodes created) that will push, pop and display data stored.
C++
Explanation / Answer
class stackList : public list {
public:
void push(int *data) {
if (head == 0) {
head = new node(data);
}
else {
node *tmp = new node(data);
tmp.put_next(head);
head = tmp;
}
node_num++;
}
int* pop() {
if (head == 0)
return;
int* item = *(int *)head->get_info();
node *tmp = head;
head = head->get_next();
delete tmp;
num_item--;
return item;
}
}
--------------------------------EDIT------------------------------------
complete code, since a small change in class list was mandetory
#include<iostream>
using namespace std;
class node {
void *info;
node *next;
public:
node (void *v) {info = v; next = 0; }
void put_next (node *n) {next = n;}
node *get_next ( ) {return next;}
void *get_info ( ) {return info;}
};
class list {
protected:
node *head;
int node_num;
public:
list ( ) { node_num = 0; head = 0;}
};
class stackList : public list {
public:
void push(int *data) {
if (head == 0) {
head = new node(data);
}
else {
node *tmp = new node(data);
tmp->put_next(head);
head = tmp;
}
node_num++;
}
int* pop() {
if (head == 0)
return 0;
int* item = (int *)head->get_info();
node *tmp = head;
head = head->get_next();
delete tmp;
node_num--;
return item;
}
void display() {
node *tmp = head;
cout << "top: ";
while (tmp != 0) {
cout << *((int*)tmp->get_info()) << endl;
tmp = tmp->get_next();
}
}
};
int main() {
stackList stack;
int *n, choice;
do {
cout << "1. Push Integer" << endl;
cout << "2. Pop Integer" << endl;
cout << "3. Display Stack" << endl;
cout << "4. Quit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch(choice) {
case 1:
n = new int[1];
cout << "Enter number: ";
cin >> n[0];
stack.push(n);
break;
case 2:
n = stack.pop();
cout << "Poped: " << *n << endl;
break;
case 3:
stack.display();
break;
}
}while(choice != 4);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.