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.
#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;
}
Comments
Leave a comment