Answer to Question #244790 in C++ for Myname

Question #244790
Write a program to implement the stack using an array and link list both.
Note: The code should have the modularity and should include following function apart from
main ():
 Push() This function inserts an element to top of the Stack.
 Pop() This function deletes an element from top of the Stack.
 Display() This function displays all the elements of the Stack by popping them one by
one.
1
Expert's answer
2021-10-02T01:36:49-0400
#include <iostream>
using namespace std;
class Node{
    public:
    int data;
    Node *next, *prev;
    Node();
    Node(int);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(int data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class Stack{
    Node *head;
    int size, maxsize;


    public:
    Stack(int);
    void Push(int);
    int Pop();
    void Display();
};
Stack::Stack(int x){
    head = NULL;
    size = 0;
    maxsize = x;
}
void Stack::Push(int data){
    if(head == NULL){
        head = new Node(data);
        size++;
    }
    else if(size < maxsize){
        Node *temp = new Node(data);
        temp->next = head;
        head = temp;
        size++;
    }
}
int Stack::Pop(){
    if(head != NULL){
        Node *temp = head, temp2 = *head;
        head = head->next;
        delete temp;
        size--;
        return temp2.data;
    }
    return (int)NULL;
}
void Stack::Display(){
    Node* curr = head;
    while(curr != NULL){
        cout<<"|"<<curr->data<<"|"<<endl<<"---\n";
        curr = curr->next;
        Pop();
    }
    cout<<endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS