Question

In: Computer Science

the purpose of the code is to implement a stack how can i convert this code...

the purpose of the code is to implement a stack

how can i convert this code in a way that these changes apply to it?

// simplify the logic of the main

// getline(cin, line) needs to be changed to a normal cin >> line;

//make a function for 'list'

// not allowed temporary stack (stack s2)

//merge the catches (errors)

// introduce another function for main

// avoid repetitive code

here is the code:

#include

#include

#include

#include

#include

using namespace std;

class Stack {

    public:

        bool isEmpty();

        int top();

        int pop();

        void push(int);

    private:

        vector elements;

};

bool Stack::isEmpty() {

    return elements.empty();

}

int Stack::top() {

    if(isEmpty()) {

        throw runtime_error("error: stack is empty");

    }

    else {

        return elements.back();

    }

}

int Stack::pop() {

    if(isEmpty()) {

        throw runtime_error("error: stack is empty");

    }

    else {

        int item = elements.back();

        elements.pop_back();

        return item;

    }

}

void Stack::push(int item) {

    elements.push_back(item);

}

int main() {

    string line, cmd;

    int val;

    Stack stack;

    cout << "stack> " << endl;

    while(getline(cin, line)) {

        if(line.find_first_not_of(" \t") == string:: npos) {

            cout << "stack> ";

            continue;

        }

        line = line.substr(line.find_first_not_of(" \t"));

        cmd = line.substr(0, line.find(" "));

        if(cmd == "push") {

            try {

                line = line.substr(line.find(" ") + 1);

                if(line.size() == 0 || line.at(0) == '-' || line.at(0) == '+' && line.find_first_of("0123456789") > 1 || line.find_first_not_of("0123456789+-") == 0) {

                    throw runtime_error("error: not a number");

                }

            

                else {

                    val = atoi(line.c_str());

                    stack.push(val);

                }

            }

            catch(runtime_error& excpt) {

                cout << excpt.what() << endl;

            }

        }

        else if(cmd == "pop") {

            try {

                val = stack.pop();

                cout << val << endl;

            }

            catch(runtime_error& excpt) {

                cout << excpt.what() << endl;

            }

        }

        else if(cmd == "top") {

            try {

                val = stack.top();

                cout << val << endl;

            }

            catch(runtime_error& excpt) {

                cout << excpt.what() << endl;

            }

        }

        else if(cmd == "list") {

            Stack s2;

            bool first = true;

            cout << "[";

            while(!stack.isEmpty()) {

                val = stack.pop();

                s2.push(val);

                if(!first) {

                    cout << ",";

                }

                cout << val;

                first = false;

            }

            cout << "]" << endl;

            while(!s2.isEmpty()) {

                stack.push(s2.pop());

            }

        }

        else if(cmd == "end") {

            break;

        }

        else {

            cin.ignore(numeric_limits::max(), '\n');

            cout << "error: invalid command" << endl;

        }

        cout << "stack> " << endl;

    }   

}

Solutions

Expert Solution

#include <bits/stdc++.h>
using namespace std;

// Declare linked list node

struct Node {
   int data;
   struct Node* link;
};
struct Node* top;

// Utility function to add an element data in the stack
// insert at the beginning
void push(int data)
{
   // create new node temp and allocate memory
   struct Node* temp;
   temp = new Node();

   // check if stack (heap) is full. Then inserting an element would
   // lead to stack overflow
   if (!temp) {
       cout << "\nHeap Overflow";
       exit(1);
   }

   // initialize data into temp data field
   temp->data = data;

   // put top pointer reference into temp link
   temp->link = top;

   // make temp as top of Stack
   top = temp;
}

// Utility function to check if the stack is empty or not
int isEmpty()
{
   return top == NULL;
}

// Utility function to return top element in a stack
int peek()
{
   // check for empty stack
   if (!isEmpty())
       return top->data;
   else
       exit(1);
}

// Utility function to pop top
// element from the stack

void pop()
{
   struct Node* temp;

   // check for stack underflow
   if (top == NULL) {
       cout << "\nStack Underflow" << endl;
       exit(1);
   }
   else {
       // top assign into temp
       temp = top;

       // assign second node to top
       top = top->link;

       // destroy connection between first and second
       temp->link = NULL;

       // release memory of top node
       free(temp);
   }
}

// Function to print all the
// elements of the stack
void display()
{
   struct Node* temp;

   // check for stack underflow
   if (top == NULL) {
       cout << "\nStack Underflow";
       exit(1);
   }
   else {
       temp = top;
       while (temp != NULL) {

           // print node data
           cout << temp->data << " ";

           // assign temp link to temp
           temp = temp->link;
       }
   }
}
int main()
{
   // push the elements of stack
   push(11);
   push(22);
   push(33);
   push(44);
   // display stack elements
   display();
   // print top elementof stack
   cout << "\nTop element is\n" << peek();
   pop();
   cout<<"\n";
   cout<<"After poping stack elements are\n";
   display();
   cout << "\nTop element is\n" << peek();
   return 0;
}


Related Solutions

Description( IN C++)!! The purpose of this challenge is to implement a stack using a Linked...
Description( IN C++)!! The purpose of this challenge is to implement a stack using a Linked List as a backing data structure Requirements Write the following structs struct Location { string name; string address; }; struct VisitNode { Location loc; VisitNode * next; }; Create a class called Stack. In this class, create a private variable VisitNode * head. This will keep track of the location of the head node. Add the following private function. This function will be used...
How do you implement stack by using linked list? No code just explain it.
How do you implement stack by using linked list? No code just explain it.
I need convert this java code to C language. There is no string can be used...
I need convert this java code to C language. There is no string can be used in C. Thank you! import java.util.Scanner; public class Nthword { public static void main( String args[] ) { String line; int word; Scanner stdin = new Scanner(System.in); while ( stdin.hasNextLine() ) { line = stdin.nextLine(); word = stdin.nextInt(); stdin.nextLine(); // get rid of the newline after the int System.out.println( "Read line: \"" + line + "\", extracting word [" + word + "]" );...
This is my current code for a question that asks: "Implement the stack methods push(x) and...
This is my current code for a question that asks: "Implement the stack methods push(x) and pop() using two queues". It works well, other than I want it to work for data of type T, not just Int's. (EXCUSE THE INDENTING... CHEGG POSTING DOESNT ALLOW PROPER CODE TO BE UPLOADED... JUST COPY PASTE IT INTO ECLIPSE IDE, HIGHLIGHT ALL CODE, PRESS COMMAND+SHIFT+F AND SHOULD AUTO-FORMAT) MY QUESTION: How could one modify this code in order to take data of type...
Why do we need a dynamic stack and How to implement a dynamic array stack? (...
Why do we need a dynamic stack and How to implement a dynamic array stack? ( Please answer in Java)
how can I save a character stack to a string and then save that string into...
how can I save a character stack to a string and then save that string into a new string arraylist in java? so if the character stack is h, e, l, l, o i want it to save "hello" to a string and then put that string into an array list.
I was trying to implement a stack for my assignment. One of the method given is...
I was trying to implement a stack for my assignment. One of the method given is this: public T[] toArray(); I need help to implement this method. The class is a generic class. I am using ArrayList to implement my stack. ArrayList<T> stack is the data structure. I want to convert everything in the ArrayList to an array. I am implementing the  public T[] toArray() interface given to me, so I can not use the JDK toArray method.
using C++. edit this code down below so that it will implement stack with linked list...
using C++. edit this code down below so that it will implement stack with linked list contains a default constructor, a copy constructor, and a destructor. #include <iostream> #include <vector> #include <string> #include <stack> #include <limits> using namespace std; class Stack { public: bool isEmpty(); int top(); int pop(); void push(int); void printList(); private: vector<int> elements; }; bool Stack::isEmpty() { return elements.empty(); } int Stack::top() { if(isEmpty()) { throw runtime_error("error: stack is empty"); } return elements.back(); } int Stack::pop() {...
Can you convert this code (Python) to C++ def decrypt(message, key): decryptedText = "" for i...
Can you convert this code (Python) to C++ def decrypt(message, key): decryptedText = "" for i in message: M = ord(i) k = int(key, 16) xor = M ^ k decryptedText += chr(xor) return decryptedText def encrypt(message, key): encryptedText = "" for i in message: M = ord(i) k = int(key, 16) xor = M ^ k encryptedText += chr(xor) return encryptedText # main function userText = input("Enter text: ") userKey = str(input("Enter a key: ")) encryptedMessage = encrypt(userText, userKey)...
3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array...
3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array using array. The starter code is as follows. The instance variables and most operations are provided. You need to implement the pop operation. Make sure that your program checks whether the stack is empty in the pop operation. The implementation can be found in the book and in our lecture slides. import java . io .*; import java . util .*; public class Stack2540Array...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT