Question

Using C++ in Visual Studios

Rewrite the code to use a Stack instead of a Queue. You will need to think about the differences in the Stack and Queue. Think about how they operate and how the nodes may differ.   Modify the code as necessary.

You will need to push to the Stack, pop from the Stack, peek at the Stack. You will need a member functions like in the example code. Your program will need to show that everything works as it is supposed to, just as the demonstration code does with the queue.

Example Code:

11 Includes we need for file and console input and output. #include <iostream> #include <fstream> // Include ctime for simple

public: // Default constructor with built in override that sets the front and back pointers to // NULL. I have included a couelse { 11 Put the data we passed in into the node. // temp->number = data; // There is now another node to put in the queue.// Delete the temp node currently marking the old front. // delete temp // Return the data from the old front node. // return// If we have displayed 10 items to the console, start a new line. // if (counter % 10 == 0) cout << endl; } { // Increment t( // If we are here, nothing was passed from the command line. We use and else // statement to provide another option to get{ // This is the function that we use to create the data file that hold the quantity of data // specified by the user. It tak// Close the file we just wrote the data too. // WriteBinary.close(); // Notify the user the file was created successfully. c// Peek to see if its empty. // if (myQueue.peekFront() != NULL) cout << myQueue.peekFront() << endl; } If we call getFront w

0 0
Add a comment Improve this question Transcribed image text
Answer #1

/*

A similar program for stack simulating the above implementation details and functional structure and working can be demonstrated by the following code as given below:

*/

#include <iostream>
#include <fstream>
#include <ctime>
#include <limits>

using namespace std;

// Data structure for stack
typedef struct Stack
{
   int maxsize;   // define max capacity of stack
   int top;      
   int *items;
}Stack;

// Utility function to initialize stack
Stack* newStack(int capacity)
{
   Stack *pt = (Stack*)malloc(sizeof(Stack));

   pt->maxsize = capacity;
   pt->top = -1;
   pt->items = (int*)malloc(sizeof(int) * capacity);

   return pt;
}

// Utility function to return the size of the stack
int size(Stack *pt)
{
   return pt->top + 1;
}

// Utility function to check if the stack is empty or not
int isEmpty(Stack *pt)
{
   return pt->top == -1;   // or return size(pt) == 0;
}

// Utility function to check if the stack is full or not
int isFull(Stack *pt)
{
   return pt->top == pt->maxsize - 1;   // or return size(pt) == pt->maxsize;
}

// Utility function to add an element x in the stack
void push(Stack *pt, int x)
{
   // check if stack is already full. Then inserting an element would
   // lead to stack overflow
   if (isFull(pt))
   {
       printf("OverFlow\nProgram Terminated\n");
       exit(EXIT_FAILURE);
   }

  
   // add an element and increments the top index
   pt->items[++pt->top] = x;
}

// Utility function to return top element in a stack
int peek(Stack *pt)
{
   // check for empty stack
   if (!isEmpty(pt))
       return pt->items[pt->top];
   else
       exit(EXIT_FAILURE);
}

// Utility function to pop top element from the stack
int pop(Stack *pt)
{
   // check for stack underflow
   if (isEmpty(pt))
   {
       printf("UnderFlow\nProgram Terminated\n");
       exit(EXIT_FAILURE);
   }

   // decrement stack size by 1 and (optionally) return the popped element
   return pt->items[pt->top--];
}

void viewStack(Stack *s1)
{
   // check for stack underflow
   if (isEmpty(s1))
   {
       printf("No Elements in the stack to view\nProgram Terminated\n");
       exit(EXIT_FAILURE);
   }

   Stack *p1 = newStack(size(s1));
// Print list
printf("Elements in the stack (from top to bottom) are : ");
while(!isEmpty(s1)){
int item = pop(s1);
printf("%d ",item);
push(p1, item);
}
  
while(!isEmpty(p1)){
int item = pop(p1);
push(s1, item);
}
cout<<endl;
}


int GetSize(int);
int CreateDataFile(int);
int DoWork(int);

int main(int argc, char* argv[])
{
if (argc == 2)
{
int size = atoi(argv[1]);

if (!size)
{
cout << "this is not a valid quantity" << endl;

size = GetSize(size);
}

DoWork(size);
}
else
{
int size = 0;

size = GetSize(size);

DoWork(size);
}

return (0);
}

int GetSize(int Size)
{
while (Size < 1 || Size > 100)
{
cout << endl;
cout << "how much data do you want to generate (1 to 100)? ";
cin >> Size;

if (cin.fail() || Size < 1 || Size > 100)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

cout << endl << "invalid option";
}

cout << endl << endl;
}

return(Size);
}

int CreateDataFile(int Size)
{
ofstream WriteBinary;
WriteBinary.open("numbers.bin", ios::binary);

if (!WriteBinary)
{
cout << "could not open binary file for writing" << endl << endl;
return (1);
}

cout << "writing file: numbers.bin" << endl << endl;

srand(time(NULL));
  
int Data = 0;

int counter = 1;

for (int i = 0; i < Size; i++)
{
Data = rand() % 100;

WriteBinary.write(reinterpret_cast<const char*>(&Data), sizeof(int));

cout << Data << "\t";
if (counter % 10 == 0)
{
cout << endl;
counter = 0;
}
counter = counter + 1;
}

WriteBinary.close();

cout << endl << endl << "the data file was created successfully" << endl;
}

int DoWork(int size)
{
CreateDataFile(size);

Stack *myStack = newStack(size);

ifstream ReadBinary;
ReadBinary.open("numbers.bin", ios::binary);

if (!ReadBinary)
{
cout << "could not open binary file for reading" << endl << endl;
exit(1);
}

int Data = 0;

while (ReadBinary)
{
ReadBinary.read((char*)&Data, sizeof(int));

if (ReadBinary.eof()) break;

push(myStack,Data);
}

viewStack(myStack);

cout<<"Value on peeking (Top of stack) the stack is : (Through method 1) ";

if (!isEmpty(myStack))
{
cout << peek(myStack) << endl;
}
  
cout<<"Value on peeking (Top of stack) the stack is : (Through method 2) ";

if (!isEmpty(myStack))
{
int data = peek(myStack);
cout << data << endl;
}
}

// OUTPUT OF A SAMPLE RUN:

how much data do you want to generate (1 to 100)? 9 writing file: numbers.bin 16 77 5 93 75 72 31 93 66 the data file was cre

// ON ALREADY PROVIDING A COMMAND LINE ARGUMENT:

writing file: numbers.bin 10 76 36 50 47 21 62 the data file was created successfully Elements in the stack (from top to bott

// PLEASE DO LIKE AND UPVOTE IF THIS WAS HELPFUL!

// THANK YOU SO MUCH IN ADVANCE!

Add a comment
Know the answer?
Add Answer to:
Using C++ in Visual Studios Rewrite the code to use a Stack instead of a Queue....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Help me solve this in C++ Rewrite the code to use array instead of linked lists....

    Help me solve this in C++ Rewrite the code to use array instead of linked lists. Please do not change anything besides the data structure. Instead of linked list use an array. The functionality should remain exactly the same. You can prepare a class if you wish but it is not required. /** * Queue implementation using linked list C style implementation ( no OOP). */ #include <cstdio> #include <cstdlib> #include <climits> #include <iostream> #define CAPACITY 100 // Queue max...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • 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...

  • //This is the implementation file queue.cpp. //This is the implementation of the template class Queue. //The...

    //This is the implementation file queue.cpp. //This is the implementation of the template class Queue. //The interface for the template class Queue is in the header file queue.h. #include <iostream> #include <cstdlib> #include <cstddef> #include "queue.h" using std::cout; namespace QueueSavitch { //Uses cstddef: template<class T> Queue<T>::Queue( ) : front(NULL), back(NULL) { //Intentionally empty. } //Uses cstddef: template<class T> bool Queue<T>::isEmpty( ) const { return (back == NULL);//front == NULL would also work } //Uses cstddef: template<class T> void Queue<T>::add(T item)...

  • Study the "Queue as linked list simple example" posted in this module. Rewrite the code to...

    Study the "Queue as linked list simple example" posted in this module. Rewrite the code to use array instead of linked lists. Please do not change anything besides the data structure. Instead of linked list use an array. The functionality should remain exactly the same. LListQueue.cpp ///--------------------------------------------------------------- /// File: LListQueue.cpp /// Purpose: Implementation file for a demonstration of a queue /// implemented as an array. Data type: Character /// Programming Language: C++ ///--------------------------------------------------------------- #include "LListQueue.h" ///-------------------------------------------- /// Function: LListQueue() ///...

  • Please answer in C++ Derive a class called Queue from the linked list described in Assignment...

    Please answer in C++ Derive a class called Queue from the linked list described in Assignment 2 (list of Dates). This means the Queue class will inherit all the properties (data and functions) of the linked list. But, since a queue allows pushing only at the back and popping at the front of the list, you will need to prevent the addition in the front and removal at the back. To do this, you must derive the Queue class in...

  • Code in C++. Can someone make it so that the code below can be compiled? ▪...

    Code in C++. Can someone make it so that the code below can be compiled? ▪ Creating an empty queue ▪ Inserting a value ▪ Removing a value ▪ Finding the size of the queue ▪ Printing the contents of the queue ▪ Adding the contents of one queue to the end of another ▪ Merging the contents of two queues into a third, new, queue Class Attributes Your class should be implemented using a linked list and should have...

  • PROBLEM: string CBQueue::dequeue( ) This method should remove and return the item at the front of...

    PROBLEM: string CBQueue::dequeue( ) This method should remove and return the item at the front of the queue- please add comments EXISTING CODE: #include // this allows you to declare and use strings #include using namespace std; struct qNode {   string data;   qNode* next;   qNode* prev; }; class CBQueue {   public:     CBQueue(); int CBQueue::getSize( ); bool CBQueue::isEmpty( );   private:     qNode* front;     qNode* rear;     int size; }; #include "CBQueue.h" CBQueue::CBQueue() { front = NULL; rear = NULL; size = 0; }...

  • HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE...

    HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE 100 #define NO_ELEMENT -999999 using namespace std; class Stack { int arr[SIZE]; // array to store Stack elements int top; public: Stack() { top = -1; } void push(int); // push an element into Stack int pop(); // pop the top element from Stack int topElement(); // get the top element void display(); // display Stack elements from top to bottom }; void Stack...

  • In C++ Implement a queue data structure using two stacks. Remember a queue has enqueue and...

    In C++ Implement a queue data structure using two stacks. Remember a queue has enqueue and dequeue functions. You could use either the array or linked list implementation for stacks and queues. Source for stack array: --------------------------------------------------- #include<iostream> #define SIZE 100 #define NO_ELEMENT -999999 using namespace std; class Stack { int arr[SIZE]; // array to store Stack elements int top; public: Stack() { top = -1; } void push(int); // push an element into Stack int pop(); // pop the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT