How to print from a FIFO queue array? - c++

I wrote a FIFO queue, but I keep getting a debug error; MS VS2008 says that:
"this application has requested the Runtime to terminate it in an unusual way"
in the debugger: Unhandled exception at 0x7c81eb33 in fifoQueue.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012f340..
The problem seems to comes from the last part of the program, where I trying to print the information stored into the FIFO queue array. it only print the first item, then crashes.
#include <iostream>
#include <fstream>
#include <string>
#include "QueType.h"
#include <queue>
using namespace std;
struct movieType
{
string name;
char genre;
};
int main()
{
movieType movie[3];
movie[0].name="snatch"; movie[0].genre='A';
movie[1].name="layer cake "; movie[1].genre='A';
movie[2].name="rasing twins "; movie[2].genre='C';
queue<movieType> PQqueue;
for (int i=0;i<3;++i)
PQqueue.push(movie[i]);
QueType<movieType> fifoQueue[3];
string Genre[3]={"Action", "Comedy", "Drama"};
movieType it;
while (!PQqueue.empty())
{
it=PQqueue.front();
PQqueue.pop();
if (it.genre == 'A')
fifoQueue[0].Enqueue(it);
else if (it.genre == 'C' )
fifoQueue[1].Enqueue(it);
else if (it.genre == 'D')
fifoQueue[2].Enqueue(it);
}
//!!! problem seems to come from here
movieType ij;
for (int i=0; i<3; ++i)
{
while(!fifoQueue[i].IsEmpty())
{
fifoQueue[i].Dequeue(ij);
cout<<ij.name<<endl;
}
}
return 0;
}
And the implementation file for QueType.h
#include <cstddef> //for NULL
#include <new> // for bad_alloc
//definition of NodeType
template <class ItemType>
struct NodeType
{
ItemType info; // store data
NodeType* next; // sotre location of data
};
//exception class used when queue is full
class FullQueue
{};
//Exception class used when queue is empty
class EmptyQueue
{};
//templated queue class
template<class ItemType>
class QueType
{
public:
QueType();
//Function: class constructor
//Precondition: none
//Postcondition: it initializes the pointers, front and rear to null
~QueType();
//Function:class destructor
//Precondition: queue has been initialized
//Postcondition: deallocate allocated memory
void MakeEmpty();
//Function: determines whether the queue is empty
//Precondition: queue has been initialized
//Postcondition:queue is empty
bool IsEmpty() const;
//Function:determines whether the queue is empty
//Precondition:queue has been initialized
//Postcondition:Function value = (queue is empty)
bool IsFull() const;
//Function:determines whether the queue is full
//Precondition:queue has been initialized
//Postcondition:Function value = (queue is full)
void Enqueue(ItemType newItem);
//Function:Adds newItem to the rear of the queue
//Precondition:queue has been initialized
//Postcondition:if (queue is full), FullQueue exception is thrown,
//else newItem is at rear of queue
void Dequeue(ItemType& item);
//Function:removes front item from the queue and returns it in item
//Precondition:queue has been initialized
//Postcondition:if (queue is empty), EmptyQueue exception is thrown
//and item is undefines, else front element has been removed from
//queue and item is a copy of removed element
private:
NodeType<ItemType>* front; //pointer points to the front to the queue
NodeType<ItemType>* rear; // pointer points to the rear of the queue
};
template<class ItemType>
QueType<ItemType>::QueType()
{
front = NULL;
rear = NULL;
}
template <class ItemType>
QueType<ItemType>::~QueType()
{
MakeEmpty();
}
template <class ItemType>
void QueType<ItemType>::MakeEmpty()
{
NodeType<ItemType>* tempPtr;//temporary pointer
while(front != NULL)
{
tempPtr=front;
front = front->next;
delete tempPtr;
}
rear = NULL;
}
template <class ItemType>
bool QueType<ItemType>::IsEmpty() const
{
return (front == NULL);
}
template <class ItemType>
bool QueType<ItemType>::IsFull() const
{
NodeType<ItemType>* location;
try
{
location = new NodeType<ItemType>;
delete location;
return false;
}
catch(std::bad_alloc exception)
{
return true;
}
}
template <class ItemType>
void QueType<ItemType>::Enqueue(ItemType newItem)
{
if (IsFull())
throw FullQueue();
else
{
NodeType<ItemType>* newNode;
newNode = new NodeType<ItemType>;
newNode ->info=newItem;
newNode->next=NULL;
if(rear== NULL)
front= newNode;
else
rear->next=newNode;
rear=newNode;
}
}
template <class ItemType>
void QueType<ItemType>::Dequeue(ItemType &item)
{
if(IsEmpty())
throw EmptyQueue();
else
{
NodeType<ItemType>* tempPtr;
tempPtr = front;
item= front->info;
if(front== NULL)
rear=NULL;
delete tempPtr;
}
}

In your Dequeue function, you delete the object pointed at by front, but you never set front to NULL, so your IsEmpty() method returns false when it shouldn't.
NodeType<ItemType>* tempPtr;
tempPtr = front;
item= front->info;
if(front== NULL)
rear=NULL;
delete tempPtr; // deleted object pointed at by front, but front not set to NULL

From your Dequeue function:
NodeType<ItemType>* tempPtr;
tempPtr = front;
item= front->info;
if(front== NULL)
rear=NULL;
delete tempPtr;
You actually never dequeue anything, you just free the front pointer. So when you loop, IsEmpty will return false so you will call Dequeue again, and access and the free again a pointer you already freed.

Related

How do I use a linkedStack to reverse an arrayQueue in c++

I'm having an issue with getting this code reversed using a linkedStack. I tried looking into it from multiple sources and found very little information that can be used to find an answer to my problem. I can understand that they are similar to one another but maybe due to me being new to coding in general, I found it very difficult to use a linkedStack with my current files.
I hope to know how I could use my current files to create a reversedQueue using a linkedStack within the arrayQueue.h and arrayQueue.cpp files.
please let me know whether I'm missing something from what I provided down below.
queueADT.h file
//Header file: queueADT.h
#ifndef _QUEUEADT_
#define _QUEUEADT_
#include "stackADT.h"
template <class ItemType>
class queueADT
{
public:
virtual void initializeQueue() = 0;
//Function to initialize the queue to an empty state.
//Postcondition: The queue is empty.
virtual bool isEmptyQueue() const = 0;
//Function to determine whether the queue is empty.
//Postcondition: Returns true if the queue is empty,
// otherwise returns false.
virtual bool isFullQueue() const = 0;
//Function to determine whether the queue is full.
//Postcondition: Returns true if the queue is full,
// otherwise returns false.
virtual ItemType front() const = 0;
//Function to return the first element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: If the queue is empty, the program
// terminates; otherwise, the first
// element of the queue is returned.
virtual ItemType back() const = 0;
//Function to return the last element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: If the queue is empty, the program
// terminates; otherwise, the last
// element of the queue is returned.
virtual void reverseQueue(const ItemType& queue) = 0;
virtual void addQueue(const ItemType& queueElement) = 0;
//Function to add queueElement to the queue.
//Precondition: The queue exists and is not full.
//Postcondition: The queue is changed and queueElement
// is added to the queue.
virtual void deleteQueue() = 0;
//Function to remove the first element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: The queue is changed and the first
// element is removed from the queue.
};
#endif
arrayQueue.h file
//Header file arrayQueue
#ifndef _ARRAYQUEUE_
#define _ARRAYQUEUE_
#include <iostream>
#include <cassert>
#include "queueADT.h"
using namespace std;
template <class ItemType>
class arrayQueue: public queueADT<ItemType>
{
public:
const arrayQueue<ItemType>& operator=(const arrayQueue<ItemType>&);
//Overload the assignment operator.
bool isEmptyQueue() const;
//Function to determine whether the queue is empty.
//Postcondition: Returns true if the queue is empty,
// otherwise returns false.
bool isFullQueue() const;
//Function to determine whether the queue is full.
//Postcondition: Returns true if the queue is full,
// otherwise returns false.
void initializeQueue();
//Function to initialize the queue to an empty state.
//Postcondition: The queue is empty.
ItemType front() const;
//Function to return the first element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: If the queue is empty, the program
// terminates; otherwise, the first
// element of the queue is returned.
ItemType back() const;
//Function to return the last element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: If the queue is empty, the program
// terminates; otherwise, the last
// element of the queue is returned.
void addQueue(const ItemType& queueElement);
//Function to add queueElement to the queue.
//Precondition: The queue exists and is not full.
//Postcondition: The queue is changed and queueElement
// is added to the queue.
void reverseQueue(const ItemType& queue);
void deleteQueue();
//Function to remove the first element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: The queue is changed and the first
// element is removed from the queue.
arrayQueue(int queueSize = 100);
//Constructor
arrayQueue(const arrayQueue<ItemType>& otherQueue);
//Copy constructor
~arrayQueue();
//Destructor
private:
int maxQueueSize; //variable to store the maximum queue size
int count; //variable to store the number of
//elements in the queue
int queueFront; //variable to point to the first
//element of the queue
int queueRear; //variable to point to the last
//element of the queue
ItemType *list; //pointer to the array that holds
//the queue elements
};
#include "arrayQueue.cpp"
#endif
arrayQueue.cpp file
template <class ItemType>
bool arrayQueue<ItemType>::isEmptyQueue() const
{
return (count == 0);
} //end isEmptyQueue
template <class ItemType>
bool arrayQueue<ItemType>::isFullQueue() const
{
return (count == maxQueueSize);
} //end isFullQueue
template <class ItemType>
void arrayQueue<ItemType>::initializeQueue()
{
queueFront = 0;
queueRear = maxQueueSize - 1;
count = 0;
} //end initializeQueue
template <class ItemType>
ItemType arrayQueue<ItemType>::front() const
{
assert(!isEmptyQueue());
return list[queueFront];
} //end front
template <class ItemType>
ItemType arrayQueue<ItemType>::back() const
{
assert(!isEmptyQueue());
return list[queueRear];
} //end back
template <class ItemType>
void arrayQueue<ItemType>::addQueue(const ItemType& newElement)
{
if (!isFullQueue())
{
queueRear = (queueRear + 1) % maxQueueSize; //use mod
//operator to advance queueRear
//because the array is circular
count++;
list[queueRear] = newElement;
}
else
cout << "Cannot add to a full queue." << endl;
} //end addQueue
// Test for reversing a queue using a linkedStack
template <class ItemType>
void arrayQueue<ItemType>::reverseQueue(const ItemType& queue) {
int n = queue.front();
linkedStack<int> st;
// Remove all the elements from queue and push them to stack
for (int i = 0; i < n; i++) {
int curr = queue.front();
queue.pop();
st.push(curr);
}
// Pop out elements from the stack and push them back to queue
for (int i = 0; i < n; i++) {
int curr = st.top();
st.pop();
queue.push(curr);
}
// Print the reversed queue
for (int i = 0; i < n; i++) {
int curr = queue.front();
queue.pop();
cout<<curr<<" ";
queue.push(curr);
}
cout<<endl;
}
template <class ItemType>
void arrayQueue<ItemType>::deleteQueue()
{
if (!isEmptyQueue())
{
count--;
queueFront = (queueFront + 1) % maxQueueSize; //use the
//mod operator to advance queueFront
//because the array is circular
}
else
cout << "Cannot remove from an empty queue." << endl;
} //end deleteQueue
//Constructor
template <class ItemType>
arrayQueue<ItemType>::arrayQueue(int queueSize)
{
if (queueSize <= 0)
{
cout << "Size of the array to hold the queue must "
<< "be positive." << endl;
cout << "Creating an array of size 100." << endl;
maxQueueSize = 100;
}
else
maxQueueSize = queueSize; //set maxQueueSize to
//queueSize
queueFront = 0; //initialize queueFront
queueRear = maxQueueSize - 1; //initialize queueRear
count = 0;
list = new ItemType[maxQueueSize]; //create the array to
//hold the queue elements
} //end constructor
//Destructor
template <class ItemType>
arrayQueue<ItemType>::~arrayQueue()
{
delete [] list;
} //end destructor
template <class ItemType>
const arrayQueue<ItemType>& arrayQueue<ItemType>::operator=
(const arrayQueue<ItemType>& otherQueue)
{
cout << "Write the definition of the function "
<< "to overload the assignment operator." << endl;
} //end assignment operator
template <class ItemType>
arrayQueue<ItemType>::arrayQueue(const arrayQueue<ItemType>& otherQueue)
{
cout << "Write the definition of the copy constructor."
<< endl;
} //end copy constructor
stackADT.h file
#ifndef _STACKADT_
#define _STACKADT_
template <class ItemType>
class stackADT
{
public:
virtual void initializeStack() = 0;
//Method to initialize the stack to an empty state.
//Postcondition: Stack is empty
virtual bool isEmptyStack() const = 0;
//Method to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
virtual bool isFullStack() const = 0;
//Method to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
virtual void push(const ItemType& newItem) = 0;
//Method to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
virtual ItemType top() const = 0;
//Method to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top element
// of the stack is returned.
virtual void pop() = 0;
//Method to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
};
#endif
linkedStack.h file
//Header File: linkedStack.h
#ifndef _LINKEDSTACK_
#define _LINKEDSTACK_
#include <iostream>
#include <cassert>
#include "stackADT.h"
using namespace std;
//Definition of the node
template <class ItemType>
struct nodeType
{
ItemType info;
nodeType<ItemType> *link;
};
template <class ItemType>
class linkedStack: public stackADT<ItemType>
{
public:
const linkedStack<ItemType>& operator=
(const linkedStack<ItemType>&);
//Overload the assignment operator.
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty;
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns false.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: The stack elements are removed;
// stackTop = nullptr;
void push(const ItemType& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
ItemType top() const;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top
// element of the stack is returned.
void pop();
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
linkedStack();
//Default constructor
//Postcondition: stackTop = nullptr;
linkedStack(const linkedStack<ItemType>& otherStack);
//Copy constructor
~linkedStack();
//Destructor
//Postcondition: All the elements of the stack are
// removed from the stack.
private:
nodeType<ItemType> *stackTop; //pointer to the stack
void copyStack(const linkedStack<ItemType>& otherStack);
//Function to make a copy of otherStack.
//Postcondition: A copy of otherStack is created and
// assigned to this stack.
};
#include "linkedStack.cpp"
#endif
linkedStack.cpp file
//Default constructor
template <class ItemType>
linkedStack<ItemType>::linkedStack()
{
stackTop = nullptr;
}
template <class ItemType>
bool linkedStack<ItemType>::isEmptyStack() const
{
return(stackTop == nullptr);
} //end isEmptyStack
template <class ItemType>
bool linkedStack<ItemType>:: isFullStack() const
{
return false;
} //end isFullStack
template <class ItemType>
void linkedStack<ItemType>:: initializeStack()
{
nodeType<ItemType> *temp; //pointer to delete the node
while (stackTop != nullptr) //while there are elements in
//the stack
{
temp = stackTop; //set temp to point to the
//current node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //deallocate memory occupied by temp
}
} //end initializeStack
template <class ItemType>
void linkedStack<ItemType>::push(const ItemType& newElement)
{
nodeType<ItemType> *newNode; //pointer to create the new node
newNode = new nodeType<ItemType>; //create the node
newNode->info = newElement; //store newElement in the node
newNode->link = stackTop; //insert newNode before stackTop
stackTop = newNode; //set stackTop to point to the
//top node
} //end push
template <class ItemType>
ItemType linkedStack<ItemType>::top() const
{
assert(stackTop != nullptr); //if stack is empty,
//terminate the program
return stackTop->info; //return the top element
}//end top
template <class ItemType>
void linkedStack<ItemType>::pop()
{
nodeType<ItemType> *temp; //pointer to deallocate memory
if (stackTop != nullptr)
{
temp = stackTop; //set temp to point to the top node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //delete the top node
}
else
cout << "Cannot remove from an empty stack." << endl;
}//end pop
template <class ItemType>
void linkedStack<ItemType>::copyStack
(const linkedStack<ItemType>& otherStack)
{
nodeType<ItemType> *newNode, *current, *last;
if (stackTop != nullptr) //if stack is nonempty, make it empty
initializeStack();
if (otherStack.stackTop == nullptr)
stackTop = nullptr;
else
{
current = otherStack.stackTop; //set current to point
//to the stack to be copied
//copy the stackTop element of the stack
stackTop = new nodeType<ItemType>; //create the node
stackTop->info = current->info; //copy the info
stackTop->link = nullptr; //set the link field of the
//node to nullptr
last = stackTop; //set last to point to the node
current = current->link; //set current to point to
//the next node
//copy the remaining stack
while (current != nullptr)
{
newNode = new nodeType<ItemType>;
newNode->info = current->info;
newNode->link = nullptr;
last->link = newNode;
last = newNode;
current = current->link;
}//end while
}//end else
} //end copyStack
//copy constructor
template <class ItemType>
linkedStack<ItemType>::linkedStack(
const linkedStack<ItemType>& otherStack)
{
stackTop = nullptr;
copyStack(otherStack);
}//end copy constructor
//destructor
template <class ItemType>
linkedStack<ItemType>::~linkedStack()
{
initializeStack();
}//end destructor
//overloading the assignment operator
template <class ItemType>
const linkedStack<ItemType>& linkedStack<ItemType>::operator=
(const linkedStack<ItemType>& otherStack)
{
if (this != &otherStack) //avoid self-copy
copyStack(otherStack);
return *this;
}//end operator=

Error missing template argument before . token linkedStackType.push(1)

Getting this error or a similar one everywhere in the code where the linkedStackType. is located. Not sure what is looking for. Error sounds look for something before the period as an argument. If somebody could clarify the error or explain what the argument should be I would appreciate it.
main.cpp
#include <iostream>
#include <cmath>
#include "linkedStack.h" using namespace std; bool isPrime(long num);
int main() {
linkedStackType<long> stack;
long num;
long temp; // long factor;
cout << "Enter a positive integer greater than 1: ";
cin >> num;
cout << endl;
while (num <= 1)
{
cout << "You must enter a positive integer greater than 1: " << endl;
cin >> num;
}
cout << "The prime factoriztion of " << num << ": ";
// ensure that "num" is prime
// use "stack" to print the prime factors of "num" in descending order
linkedStackType.push(1);
if ((num % 2) == 0) linkedStackType.push(2);
for (temp = 3; temp < num; temp++) { if ((num % temp == 0) && (isPrime(temp))) { linkedStackType.push(temp); } }
while (!linkedStackType.empty()) { cout << linkedStackType.top() << " "; linkedStackType.pop(); }
return 0; }
bool isPrime(long num) {
if (num <= 3) {
return num > 1;
} else if (num % 2 == 0 || num % 3 == 0) {
return false;
} else {
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
}
return true;
}
// write a function that returns whether "num" is prime }
linkedStack.h
//Header File: linkedStack.h
#ifndef H_StackType
#define H_StackType
#include <iostream>
#include <cassert>
#include "stackADT.h"
using namespace std;
//Definition of the node
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class linkedStackType: public stackADT<Type>
{
public:
const linkedStackType<Type>& operator=
(const linkedStackType<Type>&);
//Overload the assignment operator.
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty;
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns false.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: The stack elements are removed;
// stackTop = nullptr;
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
Type top() const;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top
// element of the stack is returned.
void pop();
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
linkedStackType();
//Default constructor
//Postcondition: stackTop = nullptr;
linkedStackType(const linkedStackType<Type>& otherStack);
//Copy constructor
~linkedStackType();
//Destructor
//Postcondition: All the elements of the stack are
// removed from the stack.
private:
nodeType<Type> *stackTop; //pointer to the stack
void copyStack(const linkedStackType<Type>& otherStack);
//Function to make a copy of otherStack.
//Postcondition: A copy of otherStack is created and
// assigned to this stack.
};
//Default constructor
template <class Type>
linkedStackType<Type>::linkedStackType()
{
stackTop = nullptr;
}
template <class Type>
bool linkedStackType<Type>::isEmptyStack() const
{
return(stackTop == nullptr);
} //end isEmptyStack
template <class Type>
bool linkedStackType<Type>:: isFullStack() const
{
return false;
} //end isFullStack
template <class Type>
void linkedStackType<Type>::initializeStack()
{
nodeType<Type> *temp; //pointer to delete the node
while (stackTop != nullptr) //while there are elements in
//the stack
{
temp = stackTop; //set temp to point to the
//current node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //deallocate memory occupied by temp
}
} //end initializeStack
template <class Type>
void linkedStackType<Type>::push(const Type& newElement)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the node
newNode->info = newElement; //store newElement in the node
newNode->link = stackTop; //insert newNode before stackTop
stackTop = newNode; //set stackTop to point to the
//top node
} //end push
template <class Type>
Type linkedStackType<Type>::top() const
{
assert(stackTop != nullptr); //if stack is empty,
//terminate the program
return stackTop->info; //return the top element
}//end top
template <class Type>
void linkedStackType<Type>::pop()
{
nodeType<Type> *temp; //pointer to deallocate memory
if (stackTop != nullptr)
{
temp = stackTop; //set temp to point to the top node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //delete the top node
}
else
cout << "Cannot remove from an empty stack." << endl;
}//end pop
template <class Type>
void linkedStackType<Type>::copyStack
(const linkedStackType<Type>& otherStack)
{
nodeType<Type> *newNode, *current, *last;
if (stackTop != nullptr) //if stack is nonempty, make it empty
initializeStack();
if (otherStack.stackTop == nullptr)
stackTop = nullptr;
else
{
current = otherStack.stackTop; //set current to point
//to the stack to be copied
//copy the stackTop element of the stack
stackTop = new nodeType<Type>; //create the node
stackTop->info = current->info; //copy the info
stackTop->link = nullptr; //set the link field of the
//node to nullptr
last = stackTop; //set last to point to the node
current = current->link; //set current to point to
//the next node
//copy the remaining stack
while (current != nullptr)
{
newNode = new nodeType<Type>;
newNode->info = current->info;
newNode->link = nullptr;
last->link = newNode;
last = newNode;
current = current->link;
}//end while
}//end else
} //end copyStack
//copy constructor
template <class Type>
linkedStackType<Type>::linkedStackType(
const linkedStackType<Type>& otherStack)
{
stackTop = nullptr;
copyStack(otherStack);
}//end copy constructor
//destructor
template <class Type>
linkedStackType<Type>::~linkedStackType()
{
initializeStack();
}//end destructor
//overloading the assignment operator
template <class Type>
const linkedStackType<Type>& linkedStackType<Type>::operator=
(const linkedStackType<Type>& otherStack)
{
if (this != &otherStack) //avoid self-copy
copyStack(otherStack);
return *this;
}//end operator=
#endif
stackADT.h
//Header file: stackADT.h
#ifndef H_StackADT
#define H_StackADT
template <class Type>
class stackADT
{
public:
virtual void initializeStack() = 0;
//Method to initialize the stack to an empty state.
//Postcondition: Stack is empty
virtual bool isEmptyStack() const = 0;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
virtual bool isFullStack() const = 0;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
virtual void push(const Type& newItem) = 0;
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
virtual Type top() const = 0;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top element
// of the stack is returned.
virtual void pop() = 0;
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
};
#endif

Invalid Conversion from 'int' to 'nodeType<int>'

I am trying to create a program that will reverse a linked list using a stack; however, I am continously getting the same error that I cannot set an node equal to an int yet I have seen multiple examples where this was possible! What could I be doing wrong?
Here is the code.
#include<iostream>
#include<fstream>
using namespace std;
#include "linkedStack.h"
nodeType<int> *head = NULL;
void traversal(linkedStackType<int>);
int main(){
linkedStackType<int> Estack;
linkedStackType<int> Ostack;
linkedStackType<int> Tstack;
Estack.initializeStack();
Ostack.initializeStack();
int num;
for (int i = 0; i < 10; i++)
{
cout << "Hello! Enter a number.\n";
cin >> num;
if (num % 2 == 0)
{
cout << "This number is even! It's going to the even stack.\n";
Estack.push(num);
}
else
{
cout << "This number is odd! It's going to the odd stack.\n";
Ostack.push(num);
}
}
traversal(Estack);
traversal(Ostack);
system("Pause");
return 0;
}
void traversal(linkedStackType<int> stack)
{
nodeType<int> *current = NULL, *first = NULL;
current = first;
while (current != NULL) {
stack.push(current->info);
current = current->link;
}
while (stack.isEmptyStack() != true){
current=stack.top();
stack.pop();
cout << current->info << " ";
}
}
linkedStack.h
#ifndef H_StackType
#define H_StackType
#include <iostream>
#include <cassert>
using namespace std;
#include "stackADT.h"
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class linkedStackType :public stackADT<Type>
{
public:
linkedStackType();
//Default constructor
//Postcondition: stackTop = NULL;
Type top() const;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top element of
// the stack is returned.
const linkedStackType<Type>& operator=
(const linkedStackType<Type>&);
//Overload the assignment operator.
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty;
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem is
// added to the top of the stack.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: The stack elements are removed;
// stackTop = NULL;
void pop();
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
linkedStackType(const linkedStackType<Type>& otherStack);
//Copy constructor
//~linkedStackType();
//Destructor
//Postcondition: All the elements of the stack are removed
private:
nodeType<Type> *stackTop; //pointer to the stack
void copyStack(const linkedStackType<Type>& otherStack);
//Function to make a copy of otherStack.
//Postcondition: A copy of otherStack is created and
// assigned to this stack.
};
template <class Type>
linkedStackType<Type>::linkedStackType()
{
stackTop = NULL;
}
template <class Type>
bool linkedStackType<Type>::isEmptyStack() const
{
return(stackTop == NULL);
} //end isEmptyStack
template <class Type>
bool linkedStackType<Type>::isFullStack() const
{
return false;
} //end isFullStack
template <class Type>
void linkedStackType<Type>::initializeStack()
{
nodeType<Type> *temp; //pointer to delete the node
while (stackTop != NULL) //while there are elements in
//the stack
{
temp = stackTop; //set temp to point to the
//current node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //deallocate memory occupied by temp
}
} //end initializeStack
template <class Type>
void linkedStackType<Type>::push(const Type& newElement)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the node
newNode->info = newElement; //store newElement in the node
newNode->link = stackTop; //insert newNode before stackTop
stackTop = newNode; //set stackTop to point to the
//top node
} //end push
template <class Type>
void linkedStackType<Type>::pop()
{
nodeType<Type> *temp; //pointer to deallocate memory
if (stackTop != NULL)
{
temp = stackTop; //set temp to point to the top node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //delete the top node
}
else
cout << "Cannot remove from an empty stack." << endl;
}//end pop
template <class Type>
Type linkedStackType<Type>::top() const
{
assert(stackTop != NULL); //if stack is empty,
//terminate the program
return stackTop->info; //return the top element
}//end top
template <class Type>
void linkedStackType<Type>::copyStack(const linkedStackType<Type>& otherStack)
{
nodeType<Type> *newNode, *current, *last;
if (stackTop != NULL) //if stack is nonempty, make it empty
initializeStack();
if (otherStack.stackTop == NULL)
stackTop = NULL;
else
{
current = otherStack.stackTop; //set current to point
//to the stack to be copied
//copy the stackTop element of the stack
stackTop = new nodeType<Type>; //create the node
stackTop->info = current->info; //copy the info
stackTop->link = NULL; //set the link field to NULL
last = stackTop; //set last to point to the node
current = current->link; //set current to point to the
//next node
//copy the remaining stack
while (current != NULL)
{
newNode = new nodeType<Type>;
newNode->info = current->info;
newNode->link = NULL;
last->link = newNode;
last = newNode;
current = current->link;
}//end while
}//end else
} //end copyStack
template <class Type>
const linkedStackType<Type>& linkedStackType<Type>::operator=(const linkedStackType<Type>& otherStack)
{
if (this != &otherStack) //avoid self-copy
copyStack(otherStack);
return *this;
}//end operator=
template <class Type>
linkedStackType<Type>::linkedStackType(const linkedStackType<Type>& otherStack)
{
stackTop = NULL;
copyStack(otherStack);
}//end copy constructor
#endif
stackADT.h
template <class Type>
class stackADT
{
public:
virtual void initializeStack() = 0;
//Method to initialize the stack to an empty state.
//Postcondition: Stack is empty.
virtual bool isEmptyStack() const = 0;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
virtual bool isFullStack() const = 0;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
virtual void push(const Type& newItem) = 0;
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem is added
// to the top of the stack.
virtual Type top() const = 0;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top element of the stack
// is returned.
virtual void pop() = 0;
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top element
// is removed from the stack.
};
Exact error on visual studio:
a value of type "int" cannot be assigned to an entity of type "nodeType *"
Any advice would be appreciated.
Firstly, you should change the Type top() const; into nodeType<Type>* top() const; in "linkedStack.h" and "stackADT.h".And you should add template <class Type>struct nodeType; in the "stackADT.h" because linkedStackType derives from stackADT.Additionally, Type top() const should be modified as follows:
template <class Type>
nodeType<Type>* linkedStackType<Type>::top() const
{
assert(stackTop != NULL); //if stack is empty,
//terminate the program
return stackTop; //return the top element
}//end top
In this way, I compile the project successfully.
However, there is some algorithm problems in the function void traversal(linkedStackType<int> stack). current and first both are NULL pointer.So what current point to when you use current -> info? I think you should modify this function void traversal(linkedStackType<int> stack).

C++ Queue from Linked List

Good evening. I have been trying to implement a Queue class in C++, taking a previously created Linked List class as a base.
Linked Linked List:
#include <cstddef>
#include <iostream>
#include <cstdio>
using namespace std;
template <class T>
class LinkedList {
public:
LinkedList() {
head = NULL;
}
~LinkedList() {
MakeEmpty();
}
struct Node {
T value;
Node *next;
};
Node* getHead() {
return head;
}
void Print();
void Insert();
void MakeEmpty();
private:
Node *head; // Head of the linked list.
};
Queue class:
#include "LinkedList.h"
template <class T>
class Queue {
public:
Queue() {
LinkedList<T>::Node *tnode = Q.getHead();
}
~Queue() {
Q.MakeEmpty();
}
void Enqueue( T x ) {
LinkedList<T>::Node *cnode = Q.getHead();
//Find the last element of Q
while( cnode -> next != NULL ) {
cnode = cnode -> next;
}
//Add x to the end of the queue
Q.Insert( x );
}
void Dequeue() {
LinkedList<T>::Node *hnode = Q.getHead();
//Rest of function
}
void Print() {
Q.PrintList();
}
private:
LinkedList<T> Q;
};
As you probably noticed, I am making them template classes. When compiling, I am told that tnode (found in the constructor of the Queue class) has not been declared in the scope. Any suggestions on how to fix this?
EDIT 1: The error message that I am getting is:
RCQueue.h: In constructor ‘Queue::Queue()’:
RCQueue.h:8:28: error: ‘tnode’ was not declared in this scope
LinkedList::Node *tnode = Q.getHead();
The main purpose of my constructor is to initialize the "head" pointer from the LinkedList class as NULL. I was also curious as to how one could go about declaring a variable of a structure that was declared in another template class.
Enqueue Algorithm :
1. Create a newNode with data and address.
2. if queue i.e front is empty
i. front = newnode;
ii. rear = newnode;
3. Else
i.rear->next = newnode;
ii.rear = newnode;
Dequeue Algorithm :
1. if queue is i.e front is NULL printf("\nQueue is Empty \n");
2. Else next element turn into front
i. struct node *temp = front ;
ii. front = front->next;
iii.free(temp);
C++ implementation :
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *next;
};
node *front = NULL;
node *rear =NULL;
void Enque(int data)
{
node *newnode = new node;
newnode->data = data;
newnode ->next = NULL;
if(front==NULL)
{
front=newnode;
rear=newnode;
}
else
{
rear->next = newnode;
rear = newnode;
}
}
void Deque()
{
struct node *temp;
if (front == NULL)
{
printf("\nQueue is Empty \n");
return;
}
else
{
temp = front;
front = front->next;
if(front == NULL) rear = NULL;
free(temp);
}
}
void display()
{
node *temp=front;
if(front==NULL)
{
printf("\nQueue is Empty \n");
}
else
{
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
cout<<endl;
}
You need typename in front of every use of the Node type in LinkedList that you reference within Queue because its dependent on the template parameter T. In specific,
template <class T>
class Queue {
public:
Queue() {
typename LinkedList<T>::Node *tnode = Q.getHead();
}
~Queue() {
Q.MakeEmpty();
}
void Enqueue( T x ) {
typename LinkedList<T>::Node *cnode = Q.getHead();
//Find the last element of Q
while( cnode -> next != NULL ) {
cnode = cnode -> next;
}
//Add x to the end of the queue
Q.Insert( x );
}
void Dequeue() {
typename LinkedList<T>::Node *hnode = Q.getHead();
//Rest of function
}
void Print() {
Q.PrintList();
}
private:
LinkedList<T> Q;
};
Notice the addition of typename before the uses of LinkedList<T>::Node.
Of course you'll also hear complaints about the missing definition of MakeEmpty() within LinkedList that is called in your Queue class, so just add a definition for it.
For more information on why typename is needed, this post explains its pretty clearly.

Traversing queue in C++

I have a C++ queue that I need to print. It's easy to print the first node and then delete it, then print the first node again which would then be the second node. But that would erase the entire list just to print it once... As a work around I created a temporary queue object which I passed to my print method and did the same thing as the first object, this would have been great except it's using pointers to make the queue dynamic, so deleting them from any object copied from the first is still deleting the same data. I'm not good with pointers yet but I'm sure there must be an easy way to do this, any suggestions?
Here's the code:
queue2 = queue1; // Temporary queue is assigned values of main queue
queue2.printQueue(); // Temporary queue is passed to print method
Here's my print method:
int numberPrinted = 0;
while (!isEmptyQueue())
{
cout << numberPrinted + 1 << ": " << front() << "\n";
deleteQueue();
numberPrinted++;
}
Queue class file:
#ifndef H_linkedQueue
#define H_linkedQueue
#include <iostream>
#include <cassert>
#include "queueADT.h"
using namespace std;
//Definition of the node
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class linkedQueueType: public queueADT<Type>
{
public:
bool operator==
(const linkedQueueType<Type>& otherQueue);
bool isEmptyQueue() const;
//Function to determine whether the queue is empty.
//Postcondition: Returns true if the queue is empty,
// otherwise returns false.
bool isFullQueue() const;
//Function to determine whether the queue is full.
//Postcondition: Returns true if the queue is full,
// otherwise returns false.
void initializeQueue();
//Function to initialize the queue to an empty state.
//Postcondition: queueFront = NULL; queueRear = NULL
Type front() const;
//Function to return the first element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: If the queue is empty, the program
// terminates; otherwise, the first
// element of the queue is returned.
Type back() const;
//Function to return the last element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: If the queue is empty, the program
// terminates; otherwise, the last
// element of the queue is returned.
void addQueue(const Type& queueElement);
//Function to add queueElement to the queue.
//Precondition: The queue exists and is not full.
//Postcondition: The queue is changed and queueElement
// is added to the queue.
void deleteQueue();
//Function to remove the first element of the queue.
//Precondition: The queue exists and is not empty.
//Postcondition: The queue is changed and the first
// element is removed from the queue.
int numberOfNodes();
// Return number of nodes in the queue.
void printQueue();
//Print the queue.
linkedQueueType();
//Default constructor
linkedQueueType(const linkedQueueType<Type>& otherQueue);
//Copy constructor
~linkedQueueType();
//Destructor
private:
nodeType<Type> *queueFront; //pointer to the front of
//the queue
nodeType<Type> *queueRear; //pointer to the rear of
//the queue
int count;
};
//Default constructor
template<class Type>
linkedQueueType<Type>::linkedQueueType()
{
queueFront = NULL; //set front to null
queueRear = NULL; //set rear to null
} //end default constructor
template<class Type>
bool linkedQueueType<Type>::isEmptyQueue() const
{
return(queueFront == NULL);
} //end
template<class Type>
bool linkedQueueType<Type>::isFullQueue() const
{
return false;
} //end isFullQueue
template <class Type>
void linkedQueueType<Type>::initializeQueue()
{
nodeType<Type> *temp;
while (queueFront!= NULL) //while there are elements left
//in the queue
{
temp = queueFront; //set temp to point to the
//current node
queueFront = queueFront->link; //advance first to
//the next node
delete temp; //deallocate memory occupied by temp
}
queueRear = NULL; //set rear to NULL
} //end initializeQueue
template <class Type>
void linkedQueueType<Type>::addQueue(const Type& newElement)
{
nodeType<Type> *newNode;
newNode = new nodeType<Type>; //create the node
newNode->info = newElement; //store the info
newNode->link = NULL; //initialize the link field to NULL
if (queueFront == NULL) //if initially the queue is empty
{
queueFront = newNode;
queueRear = newNode;
}
else //add newNode at the end
{
queueRear->link = newNode;
queueRear = queueRear->link;
}
count++;
}//end addQueue
template <class Type>
Type linkedQueueType<Type>::front() const
{
assert(queueFront != NULL);
return queueFront->info;
} //end front
template <class Type>
Type linkedQueueType<Type>::back() const
{
assert(queueRear!= NULL);
return queueRear->info;
} //end back
template <class Type>
void linkedQueueType<Type>::deleteQueue()
{
nodeType<Type> *temp;
if (!isEmptyQueue())
{
temp = queueFront; //make temp point to the
//first node
queueFront = queueFront->link; //advance queueFront
delete temp; //delete the first node
if (queueFront == NULL) //if after deletion the
//queue is empty
queueRear = NULL; //set queueRear to NULL
count--;
}
else
cout << "Cannot remove from an empty queue" << endl;
}//end deleteQueue
//Destructor
template <class Type>
linkedQueueType<Type>::~linkedQueueType()
{
//Write the definition of the destructor
} //end destructor
template <class Type>
bool linkedQueueType<Type>::operator==
(const linkedQueueType<Type>& otherQueue)
{
bool same = false;
if (count == otherQueue.count)
same = true;
return same;
} //end assignment operator
//copy constructor
template <class Type>
linkedQueueType<Type>::linkedQueueType
(const linkedQueueType<Type>& otherQueue)
{
//Write the definition of the copy constructor
}//end copy constructor
template <class Type>
int linkedQueueType<Type>::numberOfNodes()
{
return count;
}
template <class Type>
void linkedQueueType<Type>::printQueue()
{
int numberPrinted = 0;
while (!isEmptyQueue())
{
cout << numberPrinted + 1 << ": " << front() << "\n";
deleteQueue();
numberPrinted++;
}
}
#endif
Your queue's printQueue method already has access to the private internals of the queue. Instead of using the public interface to print the queue, just use the internal queueFront pointer and walk the list, printing each element.
Something like (pseudocode since this homework):
for(node* n = queueFront; n; n = n->next)
{
// Print data from node n.
}
If you're using a queue class you wrote yourself, add an iterator to it. If you're using a queue class that already has an iterator, iterate through it to print it. If you're using a queue class that doesn't have an iterator, switch to a different queue class that does.
If you're using std::queue, switch to std::list or std::deque.
There's an example on cplusplus.com that shows how to iterate through a deque:
#include <iostream>
#include <deque>
int main ()
{
std::deque<int> mydeque;
for (int i=1; i<=5; i++) mydeque.push_back(i);
std::cout << "mydeque contains:";
std::deque<int>::iterator it = mydeque.begin();
while (it != mydeque.end())
std::cout << ' ' << *it++;
std::cout << '\n';
return 0;
}
Or:
for (std::deque<int>::iterator it = mydeque.begin(); it != mydeque.end(); ++it)
// print *it here
If the queue is your own code, and assuming you can iterate over its elements internally, you could give it a friend ostream& operator<<(ostream&, const your_queue_type&) and write the elements to the output stream.
class Queue
{
public:
// methods
friend ostream& operator<<(ostream& o, const Queue& q)
{
// iterate over nodes and stream them to o: o << some_node and so on
}
};
Then
Queue q = ....;
std::cout << q << std::endl; // calls your ostream& operator<<
I do not know how useful this is but since you attach each node to the next using nodeType<Type>.link then you may want to do something like this:
int numberPrinted = 1;
nodeType<Type> *temp;
if (queueFront != NULL)
{
temp = queueFront;
do
{
cout << numberPrinted << ": " << temp->info << "\n";
numberPrinted++;
}while(temp->link!=NULL);
}
This way you can just follow the pointers without changing you queue.
here is an easy way to do it with just a pointer and a while loop
while(pointer != NULL) pointer.info pointer = pointer.next