Stacks There are two main operations associated with stacks; 1) putting things o
ID: 3816832 • Letter: S
Question
Stacks
There are two main operations associated with stacks;
1) putting things on the stack which is referred to as push,
2) taking things from the stack which is referred to as pop.
We can create a stack using linked lists if we force ourselves to insert and remove nodes only at the top of the list. One use of a stack is when you want to write a word backward. In that case, you will read the letters of the word one-by-one and as you read them will push them onto a stack. Once all letters are pushed onto the stack, then pop them back one-by-one. This will produce the letters of the word in reverse order.
Give the definition of the member function push of the class Stack.
Given the definition of the copy constructor for the class Stack.
Write a program that implements a stack. Your program will ask users to input a word letter-by-letter and then displays the word backward. Please note that you are working with letters to build the stack, thus when you read the word, you will push the letters onto the stack and when you write them, you will pop those letters one-by-one.
POST THE SOURCE CODE IN C++ AND INCLUDE A SCREENSHOT
Explanation / Answer
#include<iostream>
#include <stdio.h>
using namespace std;
// Creating a NODE Structure
struct node
{
char data;
struct node *next;
};
// Creating a class STACK
class stack
{
struct node *top;
public:
stack() // constructure
{
top=NULL;
}
void push(char); // to insert an element
char pop(); // to delete an element
void show(); // to show the stack
};
// PUSH Operation
void stack::push(char c)
{
struct node *ptr;
ptr=new node;
ptr->data=c;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
}
// POP Operation
char stack::pop()
{
struct node *temp;
if(top==NULL)
{
return '';
}
temp=top;
top=top->next;
char data = temp->data;
delete temp;
return data;
}
// Show stack
void stack::show()
{
struct node *ptr1=top;
cout<<"stack : ";
while(ptr1!=NULL)
{
cout<<ptr1->data<<" ->";
ptr1=ptr1->next;
}
cout<<"NULLn";
}
// Main function
int main()
{
stack s;
char c;
cout << "Enter a word: ";
while(1)
{
c = getchar();
if (c == ' ' || c == ' ')
{
break;
}
else
{
s.push(c);
}
}
while((c = s.pop()) != '')
{
cout << c;
}
cout << endl;
return 0;
}
Sample execution:
Enter a word: olleh
hello
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.