Question

In: Computer Science

this code is about implementing stacks , I want for someone to rewrite it totally in...

this code is about implementing stacks , I want for someone to rewrite it totally in different way

#include <iostream>
#include <stdexcept>
#include <vector>
#include <cstdlib>
using namespace std;

class Stack {
    public:
        bool isEmpty();
        // returns true if stack has no elements stored

        int top();
        // returns element from top of the stack
        // throws runtime_error("stack is empty")

        int pop();
        // returns element from top of the stack and removes it
        // throws runtime_error("stack is empty")

        void push(int);
        // puts a new element on top of the stack

    private:
        vector<int> elements;
};

//member function definitions
bool Stack::isEmpty()
{
    return elements.empty();
}

int Stack::top()
{
    if(isEmpty())
        throw runtime_error("stack is empty");
    return elements.back();
}

int Stack::pop()
{
    if(isEmpty())
        throw runtime_error("stack is empty");
    int item = elements.back();
    elements.pop_back();
    return item;
}

void Stack::push(int item)
{
    elements.push_back(item);
}
//member functions definitions end

int main()
{
    string line, cmd;
    int val;
    Stack stack;

    cout << "stack> ";
    //read line by line
    while(getline(cin, line))
    {
        //get the command

        //trim leading whitespace
        if(line.find_first_not_of(" \t") == string::npos)
        {
            // empty line
            cout << "stack> ";
            continue;
        }
        line = line.substr(line.find_first_not_of(" \t"));
        cmd = line.substr(0, line.find(" "));
        if(cmd == "push")
        {
            // remaining string
            line = line.substr(line.find(" ") + 1);
            if(line.size() == 0
                    || ( (line[0] == '-' || line[0] == '+') && line.find_first_of("0123456789") > 1)
                    || line.find_first_not_of("0123456789+-") == 0)
            {
                cout << "error: not a number" << endl;
            }
            else
            {
                val = atoi(line.c_str());
                stack.push(val);
            }
        }
        else if(cmd == "pop")
        {
            try
            {
                val = stack.pop();
                cout << val << endl;
            }
            catch(runtime_error& e)
            {
                cout << "error: " << e.what() << endl;
            }
        }
        else if(cmd == "top")
        {
            try
            {
                val = stack.top();
                cout << val << endl;
            }
            catch(runtime_error& e)
            {
                cout << "error: " << e.what() << endl;
            }
        }
        else if(cmd == "list")
        {
            Stack s2;
            bool first = true;
            cout << "[";
            /* pop repeatedly and store in another stack */
            while(! stack.isEmpty())
            {
                val = stack.pop();
                s2.push(val);
                if(!first)
                    cout << ",";
                cout << val;
                first = false;
            }
            cout << "]" << endl;
            /* restore original stack */
            while(! s2.isEmpty())
            {
                stack.push(s2.pop());
            }
        }
        else if(cmd == "end")
        {
            break;
        }
        else
        {
            cout << "error: invalid command" << endl;
        }

        cout << "stack> ";
    }

    cout << endl;
}

Solutions

Expert Solution

In given code, there is class named as "Stack" declared and all operations of stack data structure are

implemented by using vector.

Refer following different code is about implementing stacks:

#include <iostream>
using namespace std;

int stack[5];
int n=5;
int top=-1;

void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"All elements of stack are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty"<<endl;
}
int main() {
int ch, val;
do {
cout<<"1) Push element in stack"<<endl;
cout<<"2) Pop element from stack"<<endl;
cout<<"3) Display stack elements"<<endl;
cout<<"4) Exit"<<endl;

cout<<"Enter your choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {   
cout<<"Enter value to push into stack:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

In this code, there is no any class declaration and all operations of stack data structure is implemented by using Array.

This is menu driven program. I hope, you will understand.


Related Solutions

PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite...
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite the code implementing a template class using a linked list instead of an array. Note: The functionality should remain the same *************************************************************************************************************** /** * Stack implementation using array in C/procedural language. */ #include <iostream> #include <cstdio> #include <cstdlib> //#include <climits> // For INT_MIN #define SIZE 100 using namespace std; /// Create a stack with capacity of 100 elements int stack[SIZE]; /// Initially stack is...
I want you guys to rewrite this lab procedure, and it is fine if it was...
I want you guys to rewrite this lab procedure, and it is fine if it was shorter than this. An air track was fitted with two photocell bridges, one on each side of the collision region. Each bridge was operating in a gate mode timer that allows the collection of time intervals before and after collision. To ensure that friction and gravity have minimal effects, the track was leveled. Before starting the experiment, we ensured that loss in velocity was...
Need someone to rewrite this code to work in the same way: int testScore;    //Numeric test...
Need someone to rewrite this code to work in the same way: int testScore;    //Numeric test score         String input;     //To hold the user's input                 // Get the numeric test score.         input = JOptionPane.showInputDialog("Enter your numeric test score and I will tell you the grade: ");         testScore = Integer.parseInt(input);                 //Display the grade.         if (testScore < 60)            JOptionPane.showMessageDialog(null, "Your score of "+testScore+" is an F.");         else if (testScore < 70)            JOptionPane.showMessageDialog(null,...
Hello! Could someone please answer this for me? I would greatly appreciate it, and will totally...
Hello! Could someone please answer this for me? I would greatly appreciate it, and will totally like your answer! Length isn't necessarily important, just needs to be accurate and such. Thanks in advance!!!!!!! (References are needed when using examples, or include the link from where you got it and I can format the reference). "Discuss the difference in the cost of items sold by a retail shoe store, the cost of items sold by a shoe manufacturer, and the cost...
(This is for java) I need to rewrite this code that uses a while loop. public...
(This is for java) I need to rewrite this code that uses a while loop. public class Practice6 {      public static void main (String [] args) {         int sum = 2, i=2;        do { sum *= 6;    i++;    } while (i < 20); System.out.println("Total is: " + sum); }
this is my code I want the opposite i want to convert a postfix expression to...
this is my code I want the opposite i want to convert a postfix expression to infix expression #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c; } char pop(Stack *st) {   char c = st->s[st->top];   st->top--;   //(A+B)*(C+D)   return c; } /* function to check whether a character is an operator or not. this function...
NEED TO REWRITE THIS IN OOP MODE ######## HOMEWORK 19 ###### Rewrite the code in the...
NEED TO REWRITE THIS IN OOP MODE ######## HOMEWORK 19 ###### Rewrite the code in the OOP mode (class mode). ########################### lambda trick ##### first: changing label properties: after you've created a label, you ##### may want to change something about it. To do that, use configure method: ## label.configure(text = 'Yes') ## label.configure(bg = 'white', fg = 'black') ### that change the properties of a label called label. ################################################### ## from tkinter import * abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def callback(x):...
Python: I want to make the following code to prompt the user if want to run...
Python: I want to make the following code to prompt the user if want to run the software again. I am new to python, so i do not know if it works like c++. If can explain that would be much appreciated base = float(input("Enter base of the triagle: ")) Triangle_Right = float(input("Enter right side of the triagle: ")) Triangle_Left = float(input("Enter left side of the triagle: ")) height = float(input("Enter the height of the triangle: ")) perimiter = base...
I want letter about appreciation?
I want letter about appreciation?
Show the code in matlab to display an ECG graph (I do not want code that...
Show the code in matlab to display an ECG graph (I do not want code that simply calls the ecg function in matlab but how to write that kind of code)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT