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.
Related
So I have been working on a linked list class with a node struct to go along with it. the class works when I define the templated struct before the class but it does not work when it is declared within the classes' private section. I specifically need the ListNode Struct to be defined within the class private section using the template T.
#include <iostream>
using namespace std;
template <typename T>
class LinkedList
{
public:
LinkedList()
{
head = NULL;
tail = NULL;
numNodes = 0;
}
~LinkedList()
{
}
int getLength()
{
return numNodes;
}
T getNodeValue(int value)
{
ListNode<T> *indexNode;
indexNode = head;
int i = 0;
if (value < 0 || value > numNodes - 1)
{
throw;
}
while (indexNode->next != NULL)
{
if (i == value)
{
break;
}
indexNode = indexNode->next;
i++;
}
return indexNode->contents;
}
void insertNode(ListNode<T> *newNode)
{
if (head == NULL)
{
head = newNode;
tail = head;
tail->next = NULL;
numNodes++;
return;
}
if (newNode->contents <= head->contents)
{
if (head == tail)
{
head = newNode;
head->next = tail;
}
else
{
ListNode<T> *placeholder;
placeholder = head;
head = newNode;
head->next = placeholder;
}
numNodes++;
return;
}
if (newNode->contents > tail->contents)
{
if (head == tail)
{
tail = newNode;
head->next = tail;
}
else
{
ListNode<T> *placeholder;
placeholder = tail;
tail = newNode;
placeholder->next = tail;
}
numNodes++;
return;
}
ListNode<T> *indexNode;
indexNode = head;
while (indexNode->next != NULL)
{
if (newNode->contents <= indexNode->next->contents)
{
newNode->next = indexNode->next;
indexNode->next = newNode;
numNodes++;
return;
}
indexNode = indexNode->next;
}
}
private:
template <typename T>
struct ListNode
{
ListNode()
{
next = NULL;
}
ListNode(T value)
{
contents = value;
next = NULL;
}
T contents;
ListNode<T> *next;
};
ListNode<T> *head;
ListNode<T> *tail;
int numNodes;
};
#endif
Your struct ListNode doesn't have to be a template because it is already a nested type defined inside a template class.
Just define it like this:
struct ListNode
{
ListNode()
{
next = NULL;
}
ListNode(T value)
{
contents = value;
next = NULL;
}
T contents;
ListNode *next;
};
And then just use LinkedList<T>::ListNode (or just ListNode inside the class).
For instance, the members head and tail become:
ListNode *head;
ListNode *tail;
Important: You cannot define the struct in the private section if its used in public function (e.g.: void insertNode(ListNode *newNode)). Otherwise, how are you supposed to create a ListNode to call insertNode from outside the class?
so I have an assignment where I need to create a doubly linked list and then create a stack and queue class and inherit from the linkedlist class in order to create an RPN calculator. So far I have created my doubly linkedlist class and the other to classes. However, I am having trouble understanding how I will inherit and use the linked list class with the stack and queue. I will provide what I have so far.
I have gone to tutoring and have not had much help so I thought I would look for some extra help, do not want homework done for me but to just be pointed in the right direction.
Stack.h
using std::iterator;
using std::vector;
using std::string;
template<class T>
class Stack : public vector<T>
{
private:
T getElement(bool erase);
typename std::vector<T> ::iterator pEnd;
T top;
public:
Stack();
T pop();
T peek();
void push(T elem);
};
template<class T>
Stack<T>::Stack()
{
}
template<class T>
void Stack<T>::push(T elem)
{
this->push_back(elem);
}
template<class T>
T Stack<T>::peek()
{
return this->getElement(false);
}
template<class T>
T Stack<T>::pop()
{
return this->getElement(true);
}
template<class T>
T Stack<T>::getElement(bool erase)
{
this->pEnd = this->end() - 1;
T tmp;
if (this->size() > 0)
{
tmp = *this->pEnd;
if (erase) {
this->erase(pEnd);
}
}
return tmp;
}
Queue.h
using namespace std;
class Queue
{
private:
int items[MAXQUEUE];
int head;
int tail;
public:
Queue();
bool isEmpty();
bool isFull();
bool enqueue(int item);
int dequeue();
int peek();
};
Queue::Queue()
:head(QEMPTY), tail(QEMPTY)
{
}
bool Queue::isEmpty()
{
return this->head == this->tail;
}
bool Queue::isFull()
{
return this->tail == MAXQUEUE;
}
bool Queue::enqueue(int item)
{
if (this->isFull())
return false;
this->items[this->tail] = item;
tail = (tail + 1) % MAXQUEUE;
return true;
}
int Queue::dequeue()
{
if (this->isEmpty())
return EMPTY;
int item = this->items[head];
this->head = (this->head + 1) % MAXQUEUE;
return item;
}
int Queue::peek() {
return this->tail;
}
doublylinkedlist.h
using std::iterator;
using std::vector;
using std::string;
/*START OF NODE CLASS*/
/*---------------------------------------------*/
template<class T>
struct Node
{
T Data;
T Search;
T value;
Node<T>*Next;
Node<T>*Prev;
};
template<class T>
class LinkedList
{
private:
Node<T> *Head;
public:
LinkedList();
void addNode(T Data);
void deleteNode(T Search);
void insert(T Search, T value);
void printListBackwards();
void printListForwards();
};
template<class T>
LinkedList<T>::LinkedList()
{
this->Head = NULL;
}
template<class T>
void LinkedList<T>::addNode(T data)
{
if (Head == NULL)
{
Head = new Node<T>;
Head->Data = data;
Head->Next = NULL;
Head->Prev = NULL;
}
else
{
Node<T>*p = this->Head;
while (p->Next != NULL)
p = p->Next;
Node<T>*n = new Node<T>;
n->Data = data;
n->Next = NULL;
p->Next = n;
n->Prev = p;
}
}
template<class T>
void LinkedList<T>::insert(T Search, T value)
{
Node *p = Head;
while (p->Data != Search)
{
p = p->Next;
}
Node *n = new Node;
n->Data = value;
n->Next = p->Next;
p->Next = n;
}
template<class T>
void LinkedList<T>::deleteNode(T Search)
{
Node *p = Head;
while (p->Next->Data != Search)
{
p = p->Next;
}
Node *delPtr = p->Next;
p->Next = p->Next->Next;
delete delPtr;
}
template<class T>
void LinkedList<T>::printListBackwards()
{
Node<T> *p = Head;
while (p->Next != NULL)
{
p = p->Next;
}
while (p != NULL)
{
cout << p->Data<< endl;
p = p->Prev;
}
}
template<class T>
void LinkedList<T>::printListForwards()
{
Node<T> *p = Head;
while (p != NULL)
{
cout << p->Data << endl;
p = p->Next;
}
}
A doubly linked list can be added to at the head or the tail, and removed at the tail.
A stack pushes at one end (the head?) and pops at the same end (the head).
A queue pushes at one end (the tail) and pops at the other end (the head).
I need to print out the number of nodes in a linked list. My teacher said that the linked list keeps track of its data and "knows" how many nodes are in it. So, I should not need a while loop to determine the size of the linked list. I have trouble figuring out a way other than a while loop to print out the size.
this is the linked list:
template <class T>
class LinkedList
{
private:
struct ListNode
{
T data ;
struct ListNode * next;
};
ListNode *head;
public:
LinkedList() { head = nullptr; }
~LinkedList();
// Linked list operations
void insertNode(T);
bool deleteNode(T);
void displayList() const;
};
/////////// Implementation portion of linked list with template //////////////
// displayList: print all list data
template <class T>
void LinkedList<T>::displayList() const
{
ListNode * ptr = head;
while (ptr != nullptr)
{
cout << ptr->data << endl;
ptr = ptr->next;
}
}
// insertNode: add a node in list order
template <class T>
void LinkedList<T>::insertNode(T newValue)
{
ListNode *newNode;
ListNode *pCur;
ListNode *pPre = NULL;
newNode = new ListNode;
newNode->data = newValue;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
pCur = head;
pPre = nullptr;
while (pCur != nullptr && pCur->data < newValue)
{
pPre = pCur;
pCur = pCur->next;
}
if (pPre == nullptr)
{
head = newNode;
newNode->next = pCur;
}
else
{
pPre->next = newNode;
newNode->next = pCur;
}
}
}
// deleteNode: delete a node if found
template <class T>
bool LinkedList<T>::deleteNode(T toBeDeleted)
{
ListNode *pCur;
ListNode *pPre;
if (!head)
return true;
pCur = head;
pPre = NULL;
while (pCur != NULL && pCur->data < toBeDeleted)
{
pPre = pCur;
pCur = pCur->next;
}
if (pCur != NULL && pCur->data == toBeDeleted)
{
if (pPre)
pPre->next = pCur->next;
else
head = pCur->next;
delete pCur;
return true;
}
return false;
}
// destructor, delete all nodes
template <class T>
LinkedList<T>::~LinkedList()
{
ListNode *ptr = head;
while (ptr != NULL)
{
head = head->next;
delete ptr;
ptr = head;
}
}
Using the code you've defined, the size of the list is not stored by the list directly. Further to this, the main advantage of linked list is that each node does not know about the rest of the list, and storing the size would defeat the purpose of this.
However, you may have misunderstood what was asked of you in terms of not using a while loop. Each node knows that it's length is 1+(the length of it's tail), and so the more suitable implementation for getting the length of a linked list is recursion, not iteration.
Here is an example of a very simple LinkedList class, that implements the simple methods using recursion. As you can see, the code uses no iteration, only making a check for it's own data, then calling the same method for the next node. Although recursion in procedural languages is less efficient in most cases, for structures like this there is no doubting it is elegant.
#include <iostream>
template<class T>
class LinkedList
{
private:
T data;
LinkedList* next;
public:
LinkedList()
: LinkedList(T()) {
}
LinkedList(T value)
: data(value), next(nullptr) {
}
~LinkedList() {
delete next;
}
void insertNode(T newValue) {
if (!next) {
next = new LinkedList(newValue);
return;
}
next->insertNode(newValue);
}
void displayList() const {
std::cout << data << std::endl;
if (next) {
next->displayList();
}
}
T& at(int N) {
if (N == 0) {
return this->data;
}
return next->at(N-1);
}
int size() {
if (!next) {
return 1;
}
return 1+next->size();
}
};
int main(int argc, char const *argv[])
{
LinkedList<int>* test = new LinkedList<int>(0);
for (int i = 1; i < 10; ++i) {
test->insertNode(i);
}
std::cout << "List of length: " << test->size() << std::endl;
test->displayList();
return 0;
}
You'll notice I haven't included deleteNode, that's because writing it for the oversimplified class above is not possible for the case where the list only has one node. One possible way to implement this is to have a wrapper class, much like you in the original code, that is a pointer to the start of a linked list. See here.
I've gone through a bunch of threads trying to understand what is going on exactly with linked lists and bubblesort, and I think I get the bulk of it.
Right now my program is simply crashing when I get to the sort function and I am not sure why. Hopefully another set of eyes will see what I do not.
Any help is greatly appreciated.
DoublyList.h:
#include "listNode.h"
#ifndef DOUBLYLIST_H
#define DOUBLYLIST_H
template <typename T>
class DoublyList
{
public:
DoublyList();
~DoublyList();
void addFront(T d);
void addBack(T d);
T removeFront();
T removeBack();
T peak();
bool isEmpty();
int getSize();
void printList();
void sortList();
private:
ListNode<T> *front;
ListNode<T> *back;
int numOfElements;
};
template <typename T>
DoublyList<T>::DoublyList(){
front = NULL;
back = NULL;
numOfElements = 0;
}
template <typename T>
DoublyList<T>::~DoublyList(){
if(numOfElements!=0){
ListNode<T> *current;
current = front;
while (current != back)
{
ListNode<T> *temp = current;
current = current->next;
temp->next = NULL;
temp->prev = NULL;
delete temp;
numOfElements--;
}
//at this point current = back, now delete it
current->next = NULL;
current->prev = NULL;
delete current;
numOfElements--;
}
//this is a safeguard if you create a LL and then delete it without doing anything to it
else{
cout<<"deleted empty LL"<<endl;
delete front;
delete back;
}
}
template <typename T>
void DoublyList<T>::addFront(T d)
{
ListNode<T> *node = new ListNode<T>();
node->data = d;
if (isEmpty()){
back = node;
}
else{
front->prev = node;
}
node->next = front;
front = node;
++numOfElements;
}
template <typename T>
T DoublyList<T>::removeFront()
{
if (isEmpty()){
return T();
}
else
{
ListNode<T>* temp = front;
if (front->next == 0){
back = 0;
}
else
{
front->next->prev = 0;
}
front = front->next;
temp->next = 0;
T theData = temp->data;
delete temp;
--numOfElements;
return theData;
}
}
template <typename T>
void DoublyList<T>::addBack(T d)
{
ListNode<T> *node = new ListNode<T>();
node->data = d;
if (isEmpty()){
front = node;
}
else{
back->next = node;
}
node->prev = back;
back = node;
++numOfElements;
}
template <typename T>
T DoublyList<T>::removeBack()
{
if (isEmpty()) {
return T();
}
else
{
ListNode<T>* temp;
temp = back;
if (back->prev == 0){
front = 0;
}
else{
back->prev->next = 0;
}
back = back->prev;
temp->prev = 0;
T theData = temp->data;
delete temp;
--numOfElements;
return theData;
}
}
template <typename T>
T DoublyList<T>::peak()
{
if (isEmpty()) {
return T();
}
return front->data;
}
template <typename T>
int DoublyList<T>::getSize(){
return numOfElements;
}
template <typename T>
bool DoublyList<T>::isEmpty(){
if(numOfElements == 0){
return true;
}
else{
return false;
}
}
template <typename T>
void DoublyList<T>::printList(){
if(numOfElements!=0){
ListNode<T> *current = front;
while(current!=back)
{
cout<<current->data<<endl;
current = current->next;
}
cout<<back->data<<endl;
}
else{
cout<<"list is empty"<<endl;
}
}
template <typename T>
void DoublyList<T>::sortList(){
int size = getSize();
ListNode<T> *current;
ListNode<T> *dummy;
ListNode<T> *next;
if(current == NULL) return;
if(current -> next == NULL) return;
int swapped = 1;
while(swapped){
swapped = 0; //last pass unless there is a swap
while(current -> next != NULL){
if(current-> data < current -> next -> data){
swapped = 1; //swap, will need to re-enter while loop
//actual number swap
dummy -> data = current -> data;
current -> data = current -> next -> data;
current -> next -> data = dummy -> data;
}
current = current -> next;
}
}
}
#endif
listNode.h:
#include <iostream>
#ifndef LISTNODE_H
#define LISTNODE_H
using namespace std;
template <typename T>
class ListNode
{
public:
T data;//the data that we will store
ListNode();
ListNode(int d);
~ListNode();
ListNode *next;//int and ptr and the member variables
ListNode *prev;
};
template <typename T>
ListNode<T>::ListNode(int d){
data = d;
next = NULL;
prev = NULL;
}
template <typename T>
ListNode<T>::ListNode(){}
template <typename T>
ListNode<T>::~ListNode(){
delete next;
delete prev;
cout<<"deleted Node"<<endl;
}
#endif
testList.cpp
#include <iostream>
#include "doublyList.h"
#include "genericQueue.h"
int main(){
DoublyList<int> testQueue;
testQueue.addBack(3);
testQueue.addBack(5);
testQueue.addBack(2);
testQueue.addBack(10);
testQueue.addBack(1);
cout << "Before Sort: " << endl;
testQueue.printList();
cout << "After Sort: " << endl;
testQueue.sortList();
testQueue.printList();
}
The erors I could find so far are:
Your default ListNode() constructor doesn't null the next and prev pointers.
In void DoublyList<T>::sortList() you don't initialize dummy, so it just points into nowhere. Actually there is no reason to use a node list at all, you can just directly use a variable of type T.
You don't initialize current in the same function and you actually should reset current to e.g. front at the beginning of each outer loop.
You don't use next at all (and don't need to), so just remove it.
To sum it up, this is what void DoublyList<T>::sortList() could look like:
template <typename T>
void DoublyList<T>::sortList(){
int size = getSize();
ListNode<T> *current=front;
T dummy;
if (current == NULL) return;
if (current->next == NULL) return;
int swapped = 1;
while (swapped){
current = front;
swapped = 0; //last pass unless there is a swap
while (current->next != NULL){
if (current->data < current->next->data){
swapped = 1; //swap, will need to re-enter while loop
//actual number swap
dummy = current->data;
current->data = current->next->data;
current->next->data = dummy;
}
current = current->next;
}
}
}
and this is my suggestion for the ListNode constructor.
template <typename T>
ListNode<T>::ListNode() :
next(nullptr),
prev(nullptr),
data{}
{}
Besides that, I also agree with DaveB that swapping pointers is the approach you should actually use.
To start with you need to initialize current in your sort function,
current = first;
template <typename T>
void DoublyList<T>::sortList(){
ListNode<T> *current;
ListNode<T> *next;
T tmp;
current = front;
if(current == NULL) return;
if(current -> next == NULL) return;
int swapped = 1;
while(swapped){
swapped = 0; //last pass unless there is a swap
while(current->next != nullptr){
if(current->data < current->next->data){
swapped = 1; //swap, will need to re-enter while loop
//actual number swap
tmp = current->data;
current->data = current->next->data;
current->next->data = tmp;
}
current = current -> next;
}
if (swapped) // go back to start of list for next pass
current = front;
}
}
I have to write code to implement template queue
I get this error : cannot access private member declared in class
at this line
front=front->next;
this is the header file of my code where I get the error:
#include <iostream>
#pragma once
using namespace std;
typedef int Error_code;
#define SUCCESS 0
#define OVERFLOW -1
#define UNDERFLOW -2
template <class T>
class Node{
T item;
Node * next;
Node(){item=0; next=NULL;}
Node(T n){item=n; next=NULL:}
};
template <class T>
class queue
{
protected:
Node<T>* front; // pointer to front of Queue
Node<T> * rear; // pointer to rear of Queue
int count; // current number of items in Queue
public:
queue();
~queue();
bool isempty(){
//return count == 0;
if(front==NULL)
return true;
else
return false;
};
bool isfull(){return false;};
Error_code serve(){
Error_code outcome = SUCCESS;
Node<T> *p;
if(isempty()){
cout<<"empty queue";
outcome=UNDERFLOW;
}
else{
p=front;
front=front->next;
delete p;
count--;
}
return outcome;
} ;
Error_code retrieve(T &item){
Error_code outcome SUCCESS;
if(isempty())
{ // front node is empty, queue is empty
//return false;
cout<<"empty queue";
outcome=UNDERFLOW;
}
return outcome;
};
Error_code append(T item){
Node<T> * n ;
n= new Node; // create node
n->item = item; // set node pointers
n->next = NULL;
if (isempty())
{
rear=front = n;
}
else
{
rear->next = n; // else place at rear
rear = n; // have rear point to new node
}
count++;
return SUCCESS;
};
};
front is a pointer to Node, but next is a private member in Node
template <class T>
class Node{
T item; // since you didn't specify access level
Node * next; // explicitly the access is private by default
Node(){item=0; next=NULL;}
Node(T n){item=n; next=NULL:}
};
so you cannot use it in queue class:
front=front->next; // error
change it to be public or redesign the program