Circular Queue Bug Fix + Improvement Critiques - c++

The issue is portrayed clearly in the display function.I wanted to display the array items in top, but I couldn't figure out a way to do so as it was constantly being incremented.
Instead of this...:
void CircularQueue :: Display() const {
for(int i = front; i < MAX; i++) {
cout << a[i] << endl;
}
}
**I want to display the circular queue using top:**
void CircularQueue :: Display() const {
for(int i = front; i < top; i++) {
cout << a[i] << endl;
}
}
In my main function, I enqueue'd 15 items, and as a result, top incremented 15 times. So obviously there would be 5 garbage values. How can I manipulate top so that the display function shows all 10 array values?
#include <iostream>
using namespace std;
#define MAX 10
class CircularQueue {
private:
int top;
int front;
public:
//assume that the max number of items in this circular queue is 10.
int a[MAX];
CircularQueue() {top = -1; front = -1;}
int enqueue(int x);
void dequeue();
void peekFront() const;
void peekBack() const;
void Display() const;
bool isEmpty();
};
//1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
//10,11,12,13,14,15,6,7,8,9
int CircularQueue :: enqueue(int x) {
//Problem: The array is actually growing in size.
++top;
a[top%10] = x;
int y = a[top%10];
cout << "Adding " << y << " to the queue." << endl;
if(top == 0) {
front = 0;
}
return y;
}
void CircularQueue :: dequeue() {
if(top < 0) {
cout << "The queue is empty." << endl;
} else {
int x = a[top];
cout << x << " will now be removed." << endl;
for(int i = 0; i <= top - 1; i++) {
a[i] = a[i+1];
}
top--;
x = a[top];
cout << "The last element of the queue is now: " << x << endl;
}
}
bool CircularQueue :: isEmpty() {
return top < 0;
}
void CircularQueue :: peekFront() const {
if(front < 0) {
cout << "The queue is empty." << endl;
} else {
int x = a[front];
cout << "The Front value is: " << x << endl;
}
}
void CircularQueue :: peekBack() const {
if(top < 0) {
cout << "The queue is empty." << endl;
} else {
int x;
x = a[top];
cout << "The back value is: " << a[top] << endl;
}
}
void CircularQueue :: Display() const {
for(int i = front; i < MAX; i++) {
cout << a[i] << endl;
}
}
int main() {
CircularQueue Aq;
Aq.enqueue(0);
Aq.enqueue(1);
Aq.enqueue(2);
Aq.enqueue(3);
Aq.enqueue(4);
Aq.enqueue(5);
Aq.enqueue(6);
Aq.enqueue(7);
Aq.enqueue(8);
Aq.enqueue(9); Aq.Display();
Aq.enqueue(10);
Aq.enqueue(11);
Aq.enqueue(12);
Aq.enqueue(13);
Aq.enqueue(14);
Aq.enqueue(15); Aq.Display();
return 0;
}
Expected output should be:
10,11,12,13,14,15,6,7,8,9
The array size should be 10 always. But when I keep enqueueing; The array size goes beyond 10.

Related

I m not getting correct output for pre and post order

// in this code I first created nodes stored them in a que and keep on removing them as I entered their left and right children. To make a node have no further children I entered -1 while entering data. Here I am not able to understand what is wrong with my code , I am getting wrong output for preorder and postorder traversals. It would be really great if you guys could help me out.
I made a class que for queue ds and inherited it in tree class in protected mode.
#include <iostream>
#include <math.h>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
class que
{
protected:
int start;
int end;
struct node **arr;
int n;
public:
que(int x)
{
n = x;
arr = new struct node *[n];
start = -1;
end = -1;
}
void isfull()
{
if (end == n)
cout << "Queue is full !!!" << endl;
return;
}
int isempty()
{
if (start == end)
{
start = -1;
end = -1;
cout << "Queue is empty !!!" << endl;
return 1;
}
return 0;
}
void enqu(struct node *x)
{
if (end == n)
{
cout << "called" << endl;
isfull();
return;
}
end++;
arr[end] = x;
}
struct node *dequ(void)
{
struct node *q = 0;
if (start == end)
{
isempty();
return q;
}
start++;
cout << "Element removed is ->" << arr[start] << endl;
return arr[start];
}
};
class tree : protected que
{
public:
struct node *head;
struct node *ptr;
tree(int n) : que(n)
{
head = 0;
ptr = 0;
enter();
}
void create(void)
{
ptr = new struct node;
ptr->left = 0;
ptr->right = 0;
}
void enter(void)
{
struct node *p;
if (head == 0)
{
create();
cout << "Enter root element of tree -> ";
cin >> ptr->data;
head = ptr;
cout << "Enquing ptr - " << ptr << endl;
enqu(ptr);
}
while (!isempty())
{
p = dequ();
cout << "Enter left child ->";
int x;
cin >> x;
if (x != -1)
{
create();
p->left = ptr;
ptr->data = x;
cout << "Enquing ptr - " << ptr << endl;
enqu(ptr);
}
cout << "Enter right child ->";
cin >> x;
if (x != -1)
{
create();
p->right = ptr;
ptr->data = x;
cout << "Enquing ptr - " << ptr << endl;
enqu(ptr);
}
}
}
void inorder(struct node *yes)
{
if (yes != 0)
{
inorder(yes->left);
cout << "--> " << yes->data << endl;
inorder(yes->right);
}
}
void preorder(struct node *yes)
{
if (yes != 0)
{
cout << "--> " << yes->data << endl;
inorder(yes->left);
inorder(yes->right);
}
}
void postorder(struct node *yes)
{
if (yes != 0)
{
inorder(yes->left);
inorder(yes->right);
cout << "--> " << yes->data << endl;
}
}
int count(struct node *yes)
{
static int x = 0, y = 0;
if (yes == 0)
return 0;
x = count(yes->left);
y = count(yes->right);
return x + y + 1;
}
int height(struct node *yes)
{
static int a = 0, b = 0;
if (yes == 0)
return 0;
a = count(yes->left);
b = count(yes->right);
if (a > b)
return a + 1;
else
return b + 1;
}
};
int main()
{
int x;
cout << "Enter height of tree - ";
cin >> x;
int max = 0;
max = pow(2, x + 1) - 1;
tree tr(max);
cout << "Preorder traversal -- " << endl;
tr.preorder(tr.head);
cout << "Inorder traversal -- " << endl;
tr.inorder(tr.head);
cout << "Postorder traversal -- " << endl;
tr.postorder(tr.head);
cout << "\n No. of elements -- " << tr.count(tr.head);
cout << "\n Height of tree --" << tr.height(tr.head);
}
The preorder and postorder functions doesn't call themselves recursively. Instead they call the inorder function, which will lead to all but the root will be printed using inorder.

my code isnt executing visual studio 2017, c++

This is what im supposed to do:
Add the following operation to the class stackType:
void reverseStack(stackType &otherStack);
This operation copies the elements of a stack in reverse order onto
another stack.
Consider the following statements.
stackType stack1;
stackType stack2;
The statement
stack1.reverseStack(stack2);
copies the elements of stack1 onto stack2 in reverse order. That is, the
top element of stack1 is the bottom element of stack2, and so on.The
old contents of stack2 is destroyed and stack1 is unchanged.
And here is the code i have for it.
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class Type>
class stackType
{
Type s[10];
int top, n;
public:
stackType()
{
top = -1;
n = 50;
}
stackType(int size)
{
top = -1;
n = size;
}
void push(Type elt)
{
if (top < n - 1)
s[++top] = elt;
else
cout << "\n\tstack is full.Can't insert " << elt << endl;
}
void pop()
{
if (top < 0)
cout << "\n\tstack is empty.\n";
else
cout << "\n\tPoped elt : " << s[top--];
}
void display() {
for (int i = 0; i <= top; i++) {
cout << s[i] << " ";
}
cout << endl;
}
void reverseStack(stackType<Type> &otherStack) {
//Destroy content of other stack by making top to -1
otherStack.top = -1;
//Iterate the current stack and push the elements to other stack
for (int i = top; i >= 0; i--) {
otherStack.push(s[i]);
}
}
};
int main()
{
stackType<int> stack1;
stack1.push(10);
stack1.push(20);
stack1.push(30);
cout << "Stack1 content: \n";
stack1.display();
stackType<int> stack2;
stack1.reverseStack(stack2);
cout << "Stack2 content: \n";
stack2.display();
return 0;
}
The code the book gave me was this:
#include <iostream>
#include <cassert>
using namespace std;
template <class Type>
class stackADT
{
public:
virtual void initializeStack() = 0;
virtual bool isEmptyStack() const = 0;
virtual bool isFullStack() const = 0;
virtual void push(const Type& newItem) = 0;
virtual Type top() const = 0;
virtual void pop() = 0;
};
template <class Type>
class stackType : public stackADT<Type>
{
private:
int maxStackSize;
int stackTop;
Type *list;
public:
void initializeStack()
{
stackTop = 0;
cout << "stackTop " << stackTop << endl;
}
void print()
{
for (int i = 0; i < stackTop; i++)
{
cout << list[i] << endl;
}
}
bool isEmptyStack() const
{
return(stackTop == 0);
}
bool isFullStack() const
{
return(stackTop == maxStackSize);
}
void push(const Type& newItem)
{
if (!isFullStack())
{
list[stackTop] = newItem;
stackTop++;
}
else
{
cout << "Cannot add to a full stack." << endl;
}
cout << "stacktop: " << stackTop << endl;
system("pause");
}
Type top() const
{
assert(stackTop != 0); //if stack is empty, terminate the program.
return list[stackTop - 1];
}
void pop()
{
if (!isEmptyStack())
stackTop--;
else
cout << "Cannot remove from an empty stack." << endl;
cout << "pop: " << stackTop << endl;
}
stackType(int stackSize = 100)
{
if (stackSize <= 0)
{
cout << "Size of the array to hold the stack must be positive." <<
endl;
cout << "Creating an array of size 100." << endl;
maxStackSize = 100;
}
else
{
maxStackSize = stackSize;
cout << "maxStackSize " << maxStackSize << endl;
}
stackTop = 0;
list = new Type[maxStackSize];
}
stackType(const stackType<Type>& otherStack)
{
list = NULL;
copyStack(otherStack);
}
~stackType()
{
delete[] list;
}
const stackType<Type>& operator=(const stackType<Type>& otherStack)
{
if (this != &otherStack)
{
copyStack(otherStack);
}
return *this;
}
bool operator==(const stackType<Type>& otherStack) const
{
if (this == &otherStack)
{
return true;
}
else
{
if (stackTop != otherStack.stackTop)
{
return false;
}
else
{
for (int i = 0; i < stackTop; i++)
{
if (list[i] != otherStack.list[i])
{
return false;
}
return true;
}
}
}
}
void copyStack(const stackType<Type>& otherStack)
{
delete[] list;
maxStackSize = otherStack.maxStackSize;
stackTop = otherStack.stackTop;
list = new Type[maxStackSize];
//copy otherStack into this stack.
for (int j = 0; j < stackTop; j++)
{
list[j] = otherStack.list[j];
}
}
};
int main()
{
stackType<int> stack1(50);
stackType<int> stack2(50);
stack1.initializeStack();
stack1.push(23);
stack1.push(45);
stack1.push(38);
stack1.print();
stack2 = stack1;
if (stack1 == stack2)
cout << "stack1 and stack2 are identical" << endl;
else
cout << "stack1 and stack2 are not identical" << endl;
stack2.pop();
stack2.push(38);
cout << "**** After pop and push operations on stack2 ****" << endl;
if (stack1 == stack2)
cout << "stack1 and stack2 are identical" << endl;
else
cout << "stack1 and stack2 are not identical" << endl;
stack2.push(11);
cout << "**** After another push operation on stack2 ****" << endl;
if (stack1 == stack2)
cout << "stack1 and stack2 are identical" << endl;
else
cout << "stack1 and stack2 are not identical" << endl;
return 0;
}
enter image description here
You need to create a breakpoint at the end of your code (End of your main function).

C++ Depth First Search of Trie with prefix parameter

I'm trying to implement a trie that can print out the frequency of words with a given prefix.
Edit: Thanks to #kaidul-islam finding my error with the following error:
new_word->child[letter]->prefixes_++;
Below is the fixed code:
Trie Class:
class Trie
{
public:
Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
{
for (int i=0; i<26; i++)
{
child[i] = nullptr;
}
}
virtual ~Trie();
//Child nodes of characters from a-z
Trie *child[26];
//vector<Trie> child;
int prefixes_;
//accessor & mutator functions
bool GetIsLeaf() { return is_leaf_; }
void SetIsLeaf(bool val) { is_leaf_ = val; }
int GetFrequency() { return frequency_; }
void SetFrequency(int val) { frequency_ = val; }
int GetPrefixes() { return prefixes_; }
void SetPrefixes(int val) { prefixes_ = val; }
bool is_leaf_;
private:
//bool is_leaf_;
int frequency_;
};
Function in Question:
void AddWord(string &word, Trie *root)
{
Trie *new_word = root;
new_word->prefixes_++;
for(unsigned int i = 0 ; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a'; //extract character of word
if(new_word->child[letter] == nullptr)
{
new_word->child[letter] = new Trie;
}
/*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
int x = (new_word->child[letter]->GetPrefixes())+1;
cout << "value of x: " << x << endl;
new_word->child[letter]->SetPrefixes(x);*/
new_word->child[letter]->prefixes_++;
new_word = new_word->child[letter];
}
new_word->SetFrequency(new_word->GetFrequency()+1);
/*
cout << "Word: " << word << endl;
cout << "frequency: " << new_word->GetFrequency() << endl;
cout << "prefixes: " << new_word->GetPrefixes() << endl;
cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
*/
}
After a quick inspection, I found you didn't initialize member variables in your constructor.
Trie(): prefixes_(0),
is_leaf_(false),
frequency_(0) {
for(int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}
Unlike global variable, there is no guarantee that prefixes_ will be 0 by default on declaration. And child[i] is not guaranteed to be nullptr too. You need to initialize everything.

Access Violation error when I debug my priority queue program

I am getting a access violation error in my code when I try run it. The program is a priority queue that inserts a value and prints the heap after each insertion and min extract.
Header File:
#pragma once
/*
Header file for the priority queue class
*/
#ifndef PRIORITYQUEUE_H
#define PRIORITYQUEUE_H
class priorityQueue
{
private:
int size;
int *data;
public:
static const int CAPACITY = 50;
priorityQueue();//constructor
~priorityQueue();//destructor
int getParent(int index);
int getLeftChild(int index);
int getRightChild(int index);
void swap(int &, int &);
void insert(int item); //enqueue - heap_insert
void printArray(int []);
void heapify(int index);
//remove and return the smallest item currently in the priority queue
int extractMin();//dequeue
bool empty() const;
int min() const; //return the smallest item
};
#endif
Main Code:
#include <iostream>
#include "priorityQueue.h"
using namespace std;
int main()
{
priorityQueue myqueue; //class object
if (myqueue.empty())
cout << "My priority Queue is empty\n" << endl; //prompt
myqueue.insert(59); //Insert value into queue
cout << "After inserting 59 Priority Queue has" << endl;
myqueue.insert(41);
cout << "After inserting 41 Priority Queue has" << endl;
myqueue.insert(25);
cout << "After inserting 25 Priority Queue has" << endl;
myqueue.insert(12);
cout << "After inserting 12 Priority Queue has" << endl;
myqueue.insert(91);
cout << "After inserting 91 Priority Queue has" << endl;
myqueue.min();
myqueue.extractMin();
cout << "After extracting the minimum value Priority Queue has" << endl;
myqueue.insert(34);
cout << "After inserting 34 Priority Queue has" << endl;
myqueue.insert(63);
cout << "After inserting 63 Priority Queue has" << endl;
myqueue.extractMin();
cout << "After extracting the minimum value Priority Queue has" << endl;
myqueue.insert(75);
cout << "After inserting 75 Priority Queue has" << endl;
myqueue.insert(85);
cout << "After inserting 85 Priority Queue has" << endl;
myqueue.extractMin();
cout << "After extracting the minimum value Priority Queue has" << endl;
cout <<"Minimum value is " ;
cout << myqueue.min() <<endl; //prints out heap min
system("pause");
return 0;
}
priorityQueue::priorityQueue() //constructor
{
size = CAPACITY;
&data[size];
}
priorityQueue::~priorityQueue() //destructor
{
}
int priorityQueue::getParent(int index) //finds parent
{
return (index - 1) / 2;
}
int priorityQueue::getLeftChild(int index) //finds left child
{
return (2 * index) + 1;
}
int priorityQueue::getRightChild(int index) //find right child
{
return (2 * index) + 2;
}
void priorityQueue::swap(int& item1, int& item2) //swaps value of two variables
{
int temp = item1;
item1 = item2;
item2 = temp;
}
void priorityQueue::heapify(int index) //heapifies the heap
{
int largest = index;
int l = getLeftChild(index);
int r = getRightChild(index);
if (l < size && data[l] > data[index])
{
largest = l;
}
if (r < size && data[r] > data[largest])
{
largest = r;
}
if (largest != index)
{
swap(data[index], data[largest]);
heapify(data[size]);
}
}
void priorityQueue::printArray(int []) //prints array
{
for (int i = 0; i < CAPACITY; i++)
{
cout << data[i] << ", ";
}
}
int priorityQueue::extractMin() //finds min and removes it
{
int min = data[0];
data[0] = data[size - 1];
size - 1;
heapify(data[size]);
return min;
}
int priorityQueue::min() const // finds min
{
return data[0];
}
bool priorityQueue::empty() const // checks if heap is empty
{
if (data == NULL)
{
return true;
}
else
{
return false;
}
}
void priorityQueue::insert(int Item) //inserts values into heap
{
size += 1;
int i = size - 1;
while (i > 0 && data[getParent(i)] < Item)
{
data[i] = data[getParent(i)];
i = getParent(i);
}
data[i] = Item;
}
In your constructor, &data[size]; does nothing. You need to allocate some memory for it, possibly using new - data = new int[size] - or use a smart pointer.

Changing an array class to hold a dynamic array

everything i have read says this should be easy and that you just add these three lines
typedef double* DoublePtr;
DoublePtr p;
p = new double [10]
but where do i add this code? Everything i have tried just breaks my program what am I missing? I tried a set function to set the value of max size but it didn't work either
does anyone know how to do this?
#include<iostream>
using namespace std;
const int MAX_SIZE = 50;
class ListDynamic
{
public:
ListDynamic();
bool full();
int getSize();
void addValue(double value);
double getValue(int index);
double getLast();
void deleteLast();
friend ostream& operator <<(ostream& out, const ListDynamic& thisList);
private:
double listValues[MAX_SIZE];
int size;
};
int main()
{
double value;
ListDynamic l;
cout << "size of List " << l.getSize() << endl;
cout << "New size of List " << l.getSize() << endl;
cout << "First Value: " << l.getValue(0) << endl;
cout << "Last Value: " << l.getLast() << endl;
cout << "deleting last value from list" << endl;
l.deleteLast();
cout << "new list size " << l.getSize() << endl;
cout << "the list now contains: " << endl << l << endl;
system("pause");
return 0;
}
ListDynamic::ListDynamic()
{
size = 0;
}
bool ListDynamic::full()
{
return (size == MAX_SIZE);
}
int ListDynamic::getSize()
{
return size;
}
void ListDynamic::addValue(double value)
{
if (size < MAX_SIZE)
{
listValues[size] = value;
size++;
}
else
cout << "\n\n*** Error in ListDynamic Class: Attempting to add value past max limit.";
}
double ListDynamic::getValue(int index)
{
if (index < size)
return listValues[index];
else
cout << "\n\n*** Error in ListDynamic Class: Attempting to retrieve value past current size.";
}
double ListDynamic::getLast()
{
if (size > 0)
return getValue(size - 1);
else
cout << "\n\n*** Error in ListDynamic Class: Call to getLast in Empty List.";
}
void ListDynamic::deleteLast()
{
if (size > 0)
size--;
else
cout << "\n\n*** Error in ListDynamic Class: Call to deleteLast in Empty List.";
}
ostream& operator <<(ostream& out, const ListDynamic& thisList)
{
for (int i = 0; i < thisList.size; i++)
out << thisList.listValues[i] << endl;
return out;
}
You need to change listValues to a double*
double* listValues;
And when you add a value greater than the size, you'll need to reallocate the array your array and copy the elements of the former array to the new one. For example:
void ListDynamic::addValue(double value)
{
if (full())
{
double* temp = new double[size];
std::copy(listValues, listValues + size, temp);
delete[] listValues;
listValues = new double[size + 1];
std::copy(temp, temp + size, listValues);
listValues[size] = value;
delete[] temp;
} else
{
listValues[size++] = value;
}
}