Question

In: Computer Science

in C++ For this program, you are going to implement a stack using an array and...

in C++

For this program, you are going to implement a stack using an array and dynamic memory allocation.

A stack is a special type of data structure that takes in values (in our case integers) one at a time and processes them in a special order. Specifically, a stack is what's called a first-in-last-out (FILO) data structure. That is to say, the first integer inserted into the stack is the last value to be processed. The last value in the stack is the first one processed.

A stack is used as a part of many different algorithms in computer science. For now, when we say to "process" an integer on the stack, all I want you to do is print out what the integer is to the terminal, and then remove it from the array.

Here's a link for a visual on how it would work: https://www.cs.usfca.edu/~galles/visualization/StackArray.html

Here is how I want your program to work:

  • Have the program present a menu where I can either:
    • Insert a new integer onto the stack.
    • Process an integer from the stack.
    • Quit the program.
  • Every time that you present the menu, please print out the contents of the stack before I pick a menu option. If the stack is empty, please let the user know.
  • The point of this assignment is to use dynamic memory allocation. So you must use malloc at the start of the program to allocate memory for a single integer. Then use realloc for the remainder of the program. Statically declaring arrays will result in no credit for the assignment!
  • If I choose the second options, which is to process a node, please print out the value that is being processed and then use realloc to appropriately change the size of your array.
  • Be sure to use the free function to release all memory if I decide to quit the program.

You do not have to do this in a function. This can all be done in the main function if you like.

I've attached the output from my version of the program in the sampleoutput.txt file if you would like to see an example of what I'm looking for.

*****Extra credit: 10%*****

A queue is a similar data structure in which the first item inserted into the queue is the first item processed (FIFO). After I choose to quit the stack loop, reallocate the array pointer back to a single integer and then repeat the program above, but so it processes the integers in the order of a queue rather than a stack. The output should indicate that we are now using a queue as well.

Solutions

Expert Solution

#include <iostream>

#include <cstdlib>

using namespace std;

int * insert_stack(int * arr, int size, int input) {
    int * newarr = (int * ) realloc(arr, sizeof(int) * (size + 1));
    *(newarr + size) = input;
    return newarr;
}

int process_stack(int * arr, int size) {
    int x = arr[size - 1];
    arr = (int * ) realloc(arr, sizeof(int) * (size - 1));
    return x;
}

int * insert_queue(int * arr, int size, int input) {
    int * newarr = (int * ) realloc(arr, sizeof(int) * (size + 1));
    *(newarr + size) = input;
    return newarr;
}

int process_queue(int * arr, int size) {
    int x = arr[0];
    for (int i = 1; i < size; i++) {
        arr[i - 1] = arr[i];
    }
    arr = (int * ) realloc(arr, sizeof(int) * (size - 1));

    return x;
}

int main() {

    int * stack = (int * ) malloc(sizeof(int));
    int size = 0;
    cout << "Stack\n";
    while (1) {
        cout << "Enter 1 to insert\nEnter 2 to process\nEnter any key to enter Queue!\n";
        int key;
        cin >> key;
        if (key == 1) {
            int input;
            cin >> input;
            stack = insert_stack(stack, size, input);
            size++;
        } else if (key == 2) {
            if (size == 0) {
                cout << "Stack Empty!" << endl;
                continue;
            }
            cout << "Processed Element is: " << process_stack(stack, size) << endl;
            size--;
        } else {
            break;
        }
        cout << "Current Stack\n";
        for (int i = 0; i < size; i++) {
            cout << * (stack + i) << " ";
        }
        cout << endl;
    }
    //if size is not empty then free the memory
    if (size > 0)
        free(stack);
    //Now used as queue
    size = 0;
    stack = (int * ) malloc(sizeof(int));
    cout << "Queue\n";
    while (1) {
        cout << "Enter 1 to insert\nEnter 2 to process\nEnter any key to exit!\n";
        int key;
        cin >> key;
        if (key == 1) {
            int input;
            cin >> input;
            stack = insert_queue(stack, size, input);
            size++;
        } else if (key == 2) {
            if (size == 0) {
                cout << "Queue Empty!" << endl;
                continue;
            }
            cout << "Processed Element is: " << process_queue(stack, size) << endl;
            size--;
        } else {
            break;
        }
        cout << "Current Queue\n";
        for (int i = 0; i < size; i++) {
            cout << * (stack + i) << " ";
        }
        cout << endl;
    }
    if (size > 0)
        free(stack);
    return 0;
}

Steps :

1. Compile and Run the program

2. Enter 1 to insert, 2 to process, and any other key to enter Queue

3. Once in Queue enter 1 to insert, 2 to process and any other key to exit the program


Related Solutions

3.1 Implement the stack ADT using array (4 marks) 3.1.1 Implement the pop() operation in the...
3.1 Implement the stack ADT using array 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. import java . io .*; import java . util .*; public class Stack2540Array { int CAPACITY = 128; int...
sing arrays please write a program to implement the STACK concept after creating the Array, the...
sing arrays please write a program to implement the STACK concept after creating the Array, the user is to be presented with a menu to choose from a number of options such as pop, push, top, etc... elements to be added on the stack are ints between 0 and 99 include a loop to re display the options (menu) and an outer loop to restart the program Write a C++ program to implement the Stacks concept. the stack implementation is...
In C Programing Create a stack using an array. Define the index variable of the array...
In C Programing Create a stack using an array. Define the index variable of the array name to be stacktop. Initially set stacktop to -1. Next create two functions push and pop. Both take as input 3 items: a pointer to the stack in memory, stacktop, and maxstack. Make sure to inc stacktop by one and also remember that stacktop[0] is the bottom of the stack and by stack rule cannot be accessed until all the other items are popped....
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...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you will implement the functionality of a stack and a queue using a linked list. Your program must use of the declaration of the Stack and Queue class in Stack.h and Queue.h You have to implement the functionalities of queue (enq, deq, displayQueue) in a file called Queue.cpp. All the functions in Queue.cpp should follow the prototypes declared in Queue.h. Your code should make use...
Using STL stack class, implement in C++ a function that checks for balanced braces { },...
Using STL stack class, implement in C++ a function that checks for balanced braces { }, in a given string / arithmetic expressions.
Write a C++ class that implement two stacks using a single C++ array. That is, it...
Write a C++ class that implement two stacks using a single C++ array. That is, it should have functions pop_first(), pop_second(), push_first(…), push_second(…), size_first(), size_second(), …. When out of space, double the size of the array (similarly to what vector is doing). Notes: Complete all the functions in exercise_2.cpp, then submit this cpp file. pop_first() and pop_second() should throw std::out_of_range exception when stack is empty. CODE: #include <cstdio> #include <stdexcept> template <class T> class TwoStacks { public:   // Constructor, initialize...
C++ Program 1–Implement a Priority Queue(PQ) using an UNSORTED LIST. Use an array size of 10...
C++ Program 1–Implement a Priority Queue(PQ) using an UNSORTED LIST. Use an array size of 10 elements. Use a circular array: Next index after last index is 0. Add the new node to next available index in the array. When you add an element, add 1 to index (hit max index, go to index 0). Test if array in full before you add. When you remove an element, from the list, move the following elements to the left to fill...
C++(screenshot output please) Part 2 - Tree programs Program 1 Implement a tree using an array...
C++(screenshot output please) Part 2 - Tree programs Program 1 Implement a tree using an array Program 2 Implement a tree using linked list - pointer Binary Tree Program 3 - Convert program 1 to a template
C++ Write the code to implement a complete binary heap using an array ( Not a...
C++ Write the code to implement a complete binary heap using an array ( Not a vector ). Code for Max heap. Implement: AddElement, GetMax, HeapSort, ShuffleUp, ShuffleDown, etc Set array size to 31 possible integers. Add 15 elements 1,3,27,22,18,4,11,26,42,19,6,2,15,16,13 Have a default constructor that initializes the array to zeros.. The data in the heap will be double datatype. PART 2 Convert to the program to a template, test with integers, double and char please provide screenshots thank you so...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT