Answer to Question #263877 in C++ for python code

Question #263877

Make use of stack data structure to reverse a string. The user will enter a string that may have several words and then print the string in reverse.

1
Expert's answer
2021-11-11T00:06:57-0500
#include <iostream>
using namespace std;
class Node{
    public:
    char data;
    Node *next, *prev;
    Node();
    Node(char);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(char data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class Stack{
    Node *head;
    int size, maxsize;


    public:
    Stack(int);
    void Push(char);
    int Pop();
    void Display();
};
Stack::Stack(int x){
    head = NULL;
    size = 0;
    maxsize = x;
}
void Stack::Push(char 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;
        curr = curr->next;
        Pop();
    }
    cout<<endl;
}
int main(){
    char str[100];
    cout<<"Input a string to reverse\n";
    cin.getline(str, 100);
    Stack stack(100);
    int i = 0;
    while(str[i] != '\0'){
        stack.Push(str[i]);
        i++;
    }
    stack.Display();
    
    return 0;
}

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