Code is supposed to print out List of numbers user entered as list 1, tell you how long the list is, let you search for a number, and then delete a number. Once the number is deleted its supposed to save it the to List 2 and then print out the numbers. The code works up until list 2. For some reason list 1 is either not making it to list 2 or its just not printing out list 2. I would appreciate assistance figuring out why this is happening.
main.cpp
#include <iostream>
#include "circularLinkedList.h"
using namespace std;
void testCopyConstructor(circularLinkedList<int> oList);
int main()
{
circularLinkedList<int> list1, list2;
int num;
cout << "Enter number ending with -999" << endl;
cin >> num;
while (num != -999)
{
list1.insertNode(num);
cin >> num;
}
cout << endl;
cout << "List 1: ";
list1.print();
cout << endl;
cout << "Length List 1: " << list1.length() << endl;
cout << "Enter the number to be searched: ";
cin >> num;
cout << endl;
if (list1.search(num))
cout << num << " found in the list" << endl;
else
cout << num << " not in the list" << endl;
cout << "Enter the number to be deleted: ";
cin >> num;
cout << endl;
list1.deleteNode(num);
cout << "After deleting the node, "
<< "List 1: ";
list1.print();
cout << endl;
cout << "Length List 1: " << list1.length() << endl;
list2 = list1;
cout << "List 2: ";
list2.print();
cout << endl;
cout << "Length List 2: " << list2.length() << endl;
testCopyConstructor(list1);
cout << "List 1: ";
list1.print();
cout << endl;
return 0;
}
void testCopyConstructor(circularLinkedList<int> oList)
{
}
circularLinkedList.h
#ifndef H_circularLinkedList
#define H_circularLinkedList
#include <iostream>
#include <cassert>
using namespace std;
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class circularLinkedList
{
public:
const circularLinkedList<Type>& operator=
(const circularLinkedList<Type>&);
//Overloads the assignment operator.
void initializeList();
//Initializes the list to an empty state.
//Postcondition: first = nullptr, last = nullptr,
// count = 0
bool isEmptyList();
//Function to determine whether the list is empty.
//Postcondition: Returns true if the list is empty;
// otherwise, returns false.
void print() const;
int length();
//Function to return the number of nodes in the
//list.
//Postcondition: The value of count is returned.
void destroyList();
//Function to delete all the nodes from the list.
//Postcondition: first = nullptr, last = nullptr,
// count = 0
Type front();
//Function to return the first element of the list.
//Precondition: The list must exist and must not be
//empty.
//Postcondition: If the list is empty, then the
// program terminates; otherwise,
// the first element of the list is
// returned.
Type back();
//Function to return the last element of the
//list.
//Precondition: The list must exist and must not
//be empty.
//Postcondition: If the list is empty, then the
// program terminates; otherwise,
// the last element of the list is
// returned.
bool search(const Type& searchItem);
//Function to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; otherwise, it returns
// false.
void insertNode(const Type& newitem);
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list, first points to the first
// node, and last points to the last
// node of the updated list.
circularLinkedList();
//Default constructor
//Initializes the list to an empty state.
//Postcondition: first = nullptr, last = nullptr,
// count = 0
circularLinkedList(const circularLinkedList<Type>& otherList);
//Copy constructor
~circularLinkedList();
//Destructor
//Deletes all the nodes from the list.
//Postcondition: The list object is destroyed.
protected:
int count; //variable to store the number of
//elements in the list
nodeType<Type> *first; //pointer to the first node of
//the list
nodeType<Type> *last; //pointer to the last node of
//the list
private:
void copyList(const circularLinkedList<Type>& otherList);
//Function to make a copy of otherList.
//Postcondition: A copy of otherList is created
// and assigned to this list.
};
template <class Type>
bool circularLinkedList<Type>::isEmptyList()
{
return (first == NULL);
// function to determine if list is empty
}
template <class Type>
circularLinkedList<Type>::circularLinkedList() // default constructor
{
first = nullptr;
count = 0;
}
template <class Type>
void circularLinkedList<Type>::destroyList()
{
nodeType<Type> *temp;
nodeType<Type> *current = NULL;
if (first != NULL)
{
current = first->link;
first->link = NULL;
}
while (current != NULL)
{
temp = current;
current = current->link;
delete temp;
}
first = NULL; //initialize last to NULL; first has already
//been set to NULL by the while loop
count = 0;
// function to destroy the list
}
template <class Type>
void circularLinkedList<Type>::initializeList()
{
destroyList(); //if the list has any nodes, delete them
}
template <class Type>
int circularLinkedList<Type>::length()
{
return count;
// function to find the length of the list
} // end length
template <class Type>
Type circularLinkedList<Type>::front()
{
assert(first != nullptr);
return first->link->info; //return the info of the first node
}//end front
template <class Type>
Type circularLinkedList<Type>::back()
{
assert(first != nullptr);
return first->info; //return the info of the first node
}//end back
template <class Type>
bool circularLinkedList<Type>::search(const Type& searchItem)
{
nodeType<Type> *current; //pointer to traverse the list
bool found = false;
if (first != NULL)
{
current = first->link;
while (current != first && !found)
{
if (current->info >= searchItem)
found = true;
else
current = current->link;
found = (current->info == searchItem);
}
}
return found;
}
// function to search the list for a given item
//end search
template <class Type>
void circularLinkedList<Type>::insertNode(const Type& newitem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
nodeType<Type> *newNode; //pointer to create a node
bool found;
newNode = new nodeType<Type>; //create the node
newNode->info = newitem; //store newitem in the node
newNode->link = NULL; //set the link field of the node
//to NULL
if (first == NULL) //Case 1 e.g., 3
{
first = newNode;
first->link = newNode;
count++;
}
else
{
if (newitem >= first->info)//e.g., 25 > 3
{
newNode->link = first->link;
first->link = newNode;
first = newNode;
}
else
{
trailCurrent = first; //e.g., 1 < 3
current = first->link;
found = false;
while (current != first && !found)
if (current->info >= newitem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
trailCurrent->link = newNode;
newNode->link = current;
}
count++;
}
// function to insert an item into the list
}//end insertNode
template <class Type>
void circularLinkedList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if (first == NULL) //Case 1; list is empty.
cout << "Can not delete from an empty list." << endl;
else
{
found = false;
trailCurrent = first;
current = first->link;
while (current != first && !found)
if (current->info >= deleteItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
if (current == first)
{
if (first->info == deleteItem)
{
if (first == first->link)
first = NULL;
else
{
trailCurrent->link = current->link;
first = trailCurrent;
}
delete current;
count--;
}
else
cout << "The item to be deleted is not in the list." << endl;
}
else
if (current->info == deleteItem)
{
trailCurrent->link = current->link;
count--;
delete current;
}
else
cout << "Item to be deleted is not in the list." << endl;
}
// function to delete an item from the list
} //end deleteNode
//Overloading the stream insertion operator
template <class Type>
void circularLinkedList<Type>::print() const
{
nodeType<Type> *current; //pointer to traverse the list
current = first->link;
while (current != first) //while more data to print
{
cout << current->info << " ";
current = current->link;
}
cout << first->info << " ";
// function to print the list
}
template <class Type>
circularLinkedList<Type>::~circularLinkedList() // destructor
{
destroyList();
}//end destructor
template <class Type>
void circularLinkedList<Type>::copyList
(const circularLinkedList<Type>& otherList)
{
first = NULL;
copyList(otherList);
// function to copy the list
}//end copyList
//copy constructor
template<class Type>
circularLinkedList<Type>::circularLinkedList
(const circularLinkedList<Type>& otherList)
{
first = nullptr;
copyList(otherList);
}//end copy constructor
//overload the assignment operator
template <class Type>
const circularLinkedList<Type>& circularLinkedList<Type>::operator=
(const circularLinkedList<Type>& otherList)
{
if (this != &otherList) //avoid self-copy
{
copyList(otherList);
}//end else
return *this;
}
#endif
Kristina, by having copyList call copyList(otherList); recursively, you are simply going to loop forever.
Take a step back. You have already default constructed list1 and list2 in main() when you created the instances of circularLinkedList<int>. So when you make the call list2 = list1; you are invoking the copy assignment member function. In your current code your copy assignment simply calls copyList (that in itself is fine) However, your copyList is a bit thin and doesn't do what you intend, e.g. containing only:
template <class Type>
void circularLinkedList<Type>::copyList
(const circularLinkedList<Type>& otherList)
{
first = NULL;
copyList(otherList); /* what happens when you get here? */
// function to copy the list
}//end copyList
See the problem? You invoke circularLinkedList<Type>::operator=, which calls circularLinkedList<Type>::copyList and then you recursively call the same function over-and-over-and-over again.
(this is where you pay attention in the debugger -- after hitting 's' (step) in copyList only to see first = NULL; and find your back in copyList ready to execute first = NULL; again, something is wrong...)
However, overall, you are thinking correctly in terms of program structure and having the copy assignment invoke copyList, you just need to actually copy the list...
So what to do? You need to copy all nodes from the otherList reference to the new list. You can easily traverse otherList, just as you have done in print() directly above copyList, except instead of outputting each value, you need to insertNode.
(the fact that in print() you iterate beginning with first->link and not first is a bit peculiar for a circular list, but... that is more a naming issue here than anything else, the traversal works correctly)
Traversing otherList and calling insertNode in your copyList will work exactly the same as the traversal in print(). It can be something as simple as:
template <class Type>
void circularLinkedList<Type>::copyList
(const circularLinkedList<Type>& otherList)
{
nodeType<Type> *iter = otherList.first->link;
while (iter != otherList.first) {
this->insertNode (iter->info);
iter = iter->link;
}
this->insertNode (iter->info);
} //end copyList
(you can use current instead of iter if that makes more sense to you, but I find iter more descriptive of what I'm doing with the reference, but that is just a personal preference).
Now your copy assignment and copy constructor should work and be invoked properly. You don't need testCopyConstructor at all in main(). To test both the copy assignment and copy constructor, you can simply add another instance of list in main that would invoke the copy constructor as opposed to the copy assignment, e.g.
list2 = list1; /* copy assignment called */
cout << "List 2: ";
list2.print();
cout << endl;
cout << "Length List 2: " << list2.length() << endl;
cout << "List 1: ";
list1.print();
cout << endl;
circularLinkedList<int> list3 (list2); /* copy constructor called */
cout << "\nList 3: ";
list3.print();
cout << "\n";
Example Use/Output
After putting it altogether, you should be able to execute your code as intended, e.g.:
$ ./bin/llcirmain
Enter number ending with -999
1 2 3 4 5 -999
List 1: 1 2 3 4 5
Length List 1: 5
Enter the number to be searched: 4
4 found in the list
Enter the number to be deleted: 3
After deleting the node, List 1: 1 2 4 5
Length List 1: 4
List 2: 1 2 4 5
Length List 2: 4
List 1: 1 2 4 5
List 3: 1 2 4 5
Look things over and let me know if you have further questions. (and think about removing using namespace std; from the header file, you don't want to include the complete standard namespace in ever source file that may use your header).
Related
I'm trying to learn Linked List, but I encountered a problem.
below is the code for linkedlist.h file
#ifndef H_LinkedListType
#define H_LinkedListType
#include <iostream>
#include <cassert>
using namespace std;
//Definition of the node
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class linkedListIterator
{
public:
linkedListIterator();
//Default constructor
//Postcondition: current = nullptr;
linkedListIterator(nodeType<Type> *ptr);
//Constructor with a parameter.
//Postcondition: current = ptr;
Type operator*();
//Function to overload the dereferencing operator *.
//Postcondition: Returns the info contained in the node.
linkedListIterator<Type> operator++();
//Overload the pre-increment operator.
//Postcondition: The iterator is advanced to the next
// node.
bool operator==(const linkedListIterator<Type>& right) const;
//Overload the equality operator.
//Postcondition: Returns true if this iterator is equal to
// the iterator specified by right,
// otherwise it returns the value false.
bool operator!=(const linkedListIterator<Type>& right) const;
//Overload the not equal to operator.
//Postcondition: Returns true if this iterator is not
// equal to the iterator specified by
// right; otherwise it returns the value
// false.
private:
nodeType<Type> *current; //pointer to point to the current
//node in the linked list
};
template <class Type>
linkedListIterator<Type>::linkedListIterator()
{
current = nullptr;
}
template <class Type>
linkedListIterator<Type>::
linkedListIterator(nodeType<Type> *ptr)
{
current = ptr;
}
template <class Type>
Type linkedListIterator<Type>::operator*()
{
return current->info;
}
template <class Type>
linkedListIterator<Type> linkedListIterator<Type>::
operator++()
{
current = current->link;
return *this;
}
template <class Type>
bool linkedListIterator<Type>::operator==
(const linkedListIterator<Type>& right) const
{
return (current == right.current);
}
template <class Type>
bool linkedListIterator<Type>::operator!=
(const linkedListIterator<Type>& right) const
{ return (current != right.current);
}
//***************** class linkedListType ****************
template <class Type>
class linkedListType
{
public:
const linkedListType<Type>& operator=
(const linkedListType<Type>&);
//Overload the assignment operator.
void initializeList();
//Initialize the list to an empty state.
//Postcondition: first = nullptr, last = nullptr,
// count = 0;
bool isEmptyList() const;
//Function to determine whether the list is empty.
//Postcondition: Returns true if the list is empty,
// otherwise it returns false.
void print() const;
//Function to output the data contained in each node.
//Postcondition: none
int length() const;
//Function to return the number of nodes in the list.
//Postcondition: The value of count is returned.
void destroyList();
//Function to delete all the nodes from the list.
//Postcondition: first = nullptr, last = nullptr,
// count = 0;
Type front() const;
//Function to return the first element of the list.
//Precondition: The list must exist and must not be
// empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the first
// element of the list is returned.
Type back() const;
//Function to return the last element of the list.
//Precondition: The list must exist and must not be
// empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the last
// element of the list is returned.
virtual bool search(const Type& searchItem) const = 0;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the
// list, otherwise the value false is
// returned.
virtual void insertFirst(const Type& newItem) = 0;
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list,
// last points to the last node in the list,
// and count is incremented by 1.
virtual void insertLast(const Type& newItem) = 0;
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem
// is inserted at the end of the list,
// last points to the last node in the
// list, and count is incremented by 1.
virtual void deleteNode(const Type& deleteItem) = 0;
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the list.
// first points to the first node, last
// points to the last node of the updated
// list, and count is decremented by 1.
linkedListIterator<Type> begin();
//Function to return an iterator at the begining of
//the linked list.
//Postcondition: Returns an iterator such that current
// is set to first.
linkedListIterator<Type> end();
//Function to return an iterator one element past the
//last element of the linked list.
//Postcondition: Returns an iterator such that current
// is set to nullptr.
linkedListType();
//Default constructor
//Initializes the list to an empty state.
//Postcondition: first = nullptr, last = nullptr,
// count = 0;
linkedListType(const linkedListType<Type>& otherList);
//copy constructor
~linkedListType();
//Destructor
//Deletes all the nodes from the list.
//Postcondition: The list object is destroyed.
protected:
int count; //variable to store the number of
//elements in the list
nodeType<Type> *first; //pointer to the first node of the list
nodeType<Type> *last; //pointer to the last node of the list
private:
void copyList(const linkedListType<Type>& otherList);
//Function to make a copy of otherList.
//Postcondition: A copy of otherList is created and
// assigned to this list.
};
template <class Type>
bool linkedListType<Type>::isEmptyList() const
{
return (first == nullptr);
}
template <class Type>
linkedListType<Type>::linkedListType() //default constructor
{
first = nullptr;
last = nullptr;
count = 0;
}
template <class Type>
void linkedListType<Type>::destroyList()
{
nodeType<Type> *temp; //pointer to deallocate the memory
//occupied by the node
while (first != nullptr) //while there are nodes in
{ //the list
temp = first; //set temp to the current node
first = first->link; //advance first to the next node
delete temp; //deallocate the memory occupied by temp
}
last = nullptr; //initialize last to nullptr; first has
//already been set to nullptr by the while loop
count = 0;
}
template <class Type>
void linkedListType<Type>::initializeList()
{
destroyList(); //if the list has any nodes, delete them
}
template <class Type>
void linkedListType<Type>::print() const
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current so that it points to
//the first node
while (current != nullptr) //while more data to print
{
cout << current->info << " ";
current = current->link;
}
}//end print
template <class Type>
int linkedListType<Type>::length() const
{
return count;
} //end length
template <class Type>
Type linkedListType<Type>::front() const
{
assert(first != nullptr);
return first->info; //return the info of the first node
}//end front
template <class Type>
Type linkedListType<Type>::back() const
{
assert(last != nullptr);
return last->info; //return the info of the last node
}//end back
template <class Type>
linkedListIterator<Type> linkedListType<Type>::begin()
{
linkedListIterator<Type> temp(first);
return temp;
}
template <class Type>
linkedListIterator<Type> linkedListType<Type>::end()
{
linkedListIterator<Type> temp(nullptr);
return temp;
}
template <class Type>
void linkedListType<Type>::copyList
(const linkedListType<Type>& otherList)
{
nodeType<Type> *newNode; //pointer to create a node
nodeType<Type> *current; //pointer to traverse the list
if (first != nullptr) //if the list is nonempty, make it empty
destroyList();
if (otherList.first == nullptr) //otherList is empty
{
first = nullptr;
last = nullptr;
count = 0;
}
else
{
current = otherList.first; //current points to the
//list to be copied
count = otherList.count;
//copy the first node
first = new nodeType<Type>; //create the node
first->info = current->info; //copy the info
first->link = nullptr; //set the link field of
//the node to nullptr
last = first; //make last point to the
//first node
current = current->link; //make current point to
//the next node
//copy the remaining list
while (current != nullptr)
{
newNode = new nodeType<Type>; //create a node
newNode->info = current->info; //copy the info
newNode->link = nullptr; //set the link of
//newNode to nullptr
last->link = newNode; //attach newNode after last
last = newNode; //make last point to
//the actual last node
current = current->link; //make current point
//to the next node
}//end while
}//end else
}//end copyList
template <class Type>
linkedListType<Type>::~linkedListType() //destructor
{
destroyList();
}//end destructor
template <class Type>
linkedListType<Type>::linkedListType
(const linkedListType<Type>& otherList)
{
first = nullptr;
copyList(otherList);
}//end copy constructor
//overload the assignment operator
template <class Type>
const linkedListType<Type>& linkedListType<Type>::operator=
(const linkedListType<Type>& otherList)
{
if (this != &otherList) //avoid self-copy
{
copyList(otherList);
}//end else
return *this;
}
#endif
Below is the code for the testProgLinkedList.cpp
//This program tests various operation of a linked list
//34 62 21 90 66 53 88 24 10 -999
#include <iostream> //Line 1
#include "unorderedLinkedList.h" //Line 2
using namespace std; //Line 3
int main() //Line 4
{ //Line 5
unorderedLinkedList<int> list1, list2; //Line 6
int num; //Line 7
cout << "Line 8: Enter integers ending "
<< "with -999" << endl; //Line 8
cin >> num; //Line 9
while (num != -999) //Line 10
{ //Line 11
list1.insertLast(num); //Line 12
cin >> num; //Line 13
} //Line 14
cout << endl; //Line 15
cout << "Line 16: list1: "; //Line 16
list1.print(); //Line 17
cout << endl; //Line 18
cout << "Line 19: Length of list1: "
<< list1.length() << endl; //Line 19
list2 = list1; //test the assignment operator Line 20
cout << "Line 21: list2: "; //Line 21
list2.print(); //Line 22
cout << endl; //Line 23
cout << "Line 24: Length of list2: "
<< list2.length() << endl; //Line 24
cout << "Line 25: Enter the number to be "
<< "deleted: "; //Line 25
cin >> num; //Line 26
cout << endl; //Line 27
list2.deleteNode(num); //Line 28
cout << "Line 29: After deleting " << num
<< " list2: " << endl; //Line 29
list2.print(); //Line 30
cout << endl; //Line 31
cout << "Line 32: Length of list2: "
<< list2.length() << endl; //Line 32
cout << endl << "Line 33: Output list1 "
<< "using an iterator" << endl; //Line 33
linkedListIterator<int> it; //Line 34
for (it = list1.begin(); it != list1.end();
++it) //Line 35
cout << *it << " "; //Line 36
cout << endl; //Line 37
return 0; //Line 38
} //Line 39
Below is the code for the unorderedLinkList.h file
#ifndef H_UnorderedLinkedList
#define H_UnorderedLinkedList
#include "linkedList.h"
using namespace std;
template <class Type>
class unorderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the
// list, otherwise the value false is
// returned.
void insertFirst(const Type& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list,
// last points to the last node in the
// list, and count is incremented by 1.
void insertLast(const Type& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem
// is inserted at the end of the list,
// last points to the last node in the
// list, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the list.
// first points to the first node, last
// points to the last node of the updated
// list, and count is decremented by 1.
};
template <class Type>
bool unorderedLinkedList<Type>::
search(const Type& searchItem) const
{
nodeType<Type> *current; //pointer to traverse the list
bool found = false;
current = first; //set current to point to the first
//node in the list
while (current != nullptr && !found) //search the list
if (current->info == searchItem) //searchItem is found
found = true;
else
current = current->link; //make current point to
//the next node
return found;
}//end search
template <class Type>
void unorderedLinkedList<Type>::insertFirst(const Type& newItem)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = first; //insert newNode before first
first = newNode; //make first point to the
//actual first node
count++; //increment count
if (last == nullptr) //if the list was empty, newNode is also
//the last node in the list
last = newNode;
}//end insertFirst
template <class Type>
void unorderedLinkedList<Type>::insertLast(const Type& newItem)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = nullptr; //set the link field of newNode
//to nullptr
if (first == nullptr) //if the list is empty, newNode is
//both the first and last node
{
first = newNode;
last = newNode;
count++; //increment count
}
else //the list is not empty, insert newNode after last
{
last->link = newNode; //insert newNode after last
last = newNode; //make last point to the actual
//last node in the list
count++; //increment count
}
}//end insertLast
template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if (first == nullptr) //Case 1; the list is empty.
cout << "Cannot delete from an empty list."
<< endl;
else
{
if (first->info == deleteItem) //Case 2
{
current = first;
first = first->link;
count--;
if (first == nullptr) //the list has only one node
last = nullptr;
delete current;
}
else //search the list for the node with the given info
{
found = false;
trailCurrent = first; //set trailCurrent to point
//to the first node
current = first->link; //set current to point to
//the second node
while (current != nullptr && !found)
{
if (current->info != deleteItem)
{
trailCurrent = current;
current = current-> link;
}
else
found = true;
}//end while
if (found) //Case 3; if found, delete the node
{
trailCurrent->link = current->link;
count--;
if (last == current) //node to be deleted
//was the last node
last = trailCurrent; //update the value
//of last
delete current; //delete the node from the list
}
else
cout << "The item to be deleted is not in "
<< "the list." << endl;
}//end else
}//end else
}//end deleteNode
#endif
But when I compiled the code it showed error messages as seen below:
I don't know how to fix the errors as I am new to coding. Please help me.
Error messages
Generally speaking you can ignore all the errors after the first couple. Fix errors one at a time starting with the first.
This line
current = first; //set current to point to the first
//node in the list
generates an error which says that the compiler doesn't know what first is. Now it looks like there is a declaration of first in linkedListType<Type> but the compiler doesn't find it. Why? Well that is complicated, but basically it is because your class is a template and the name is defined in a parent template class. Fortunately there is a simple fix, just add this->
current = this->first; //set current to point to the first
//node in the list
More details here, but be warned it's complicated.
below is the problem in one of the header of a code:
#include <iostream>
#include <fstream>
#include <string>
#include "extPersonType.h"
#include "orderedLinkedList.h"
using namespace std;
class addressBookType: public orderedLinkedListType
{
public:
void print() const;
void printNameInTheMonth(int month);
void printInfoOf(string lName);
void printNamesWithStatus(string status);
void printNamesBetweenLastNames(string last1,
string last2);
void insertNode(const extPersonType& eP);
void searchName(string lName);
void saveData(ofstream&);
addressBookType();
private:
nodeType* searchList(string lName);
};
void addressBookType::print() const
{
nodeType* current = first;
while (current != NULL)
{
current->info.printInfo();
cout << endl;
current= current->link;
}
}
void addressBookType::printNameInTheMonth(int month)
{
nodeType* current = first;
while(current != NULL)
{
if (current->info.isMonth(month))
{
current->info.print();
cout << endl;
}
current = current->link;
}
}
void addressBookType::printInfoOf(string lName)
{
nodeType* location = searchList(lName);
if (location != NULL)
location->info.printInfo();
else
cout << lName << " is not in address book." << endl;
}
void addressBookType::printNamesWithStatus(string status)
{
nodeType* current = first;
while (current != NULL)
{
if (current->info.isStatus(status))
{
current->info.print();
cout << endl;
}
current = current->link;
}
}
void addressBookType::printNamesBetweenLastNames(string last1,
string last2)
{
string lName;
nodeType* current = first;
while(current != NULL)
{
lName = current->info.getLastName();
if (last1 <= lName && lName <= last2)
{
current->info.print();
cout << endl;
}
current = current->link;
}
}
void addressBookType::insertNode(const extPersonType& eP)
{
orderedLinkedListType::insertNode(eP);
}
void addressBookType::searchName(string lName)
{
nodeType* location = searchList(lName);
if (location != NULL)
cout << lName << " is in the address book" << endl;
else
cout << lName << " is not in the address book" << endl;
}
nodeType* addressBookType::searchList(string lName)
{
nodeType* current = first;
bool found = false;
while (current != NULL)
{
if (current->info.isLastName(lName))
{
found = true;
break;
}
current = current->link;
}
return current;
}
void addressBookType::saveData(ofstream& outFile)
{
string firstN;
string lastN;
int month;
int day;
int year;
string street;
string city;
string state;
string zip;
string phone;
string pStatus;
nodeType* current = first;
while (current != NULL)
{
current->info.getDOB(month, day, year);
current->info.getAddress(street,city,state,zip);
current->info.getPhoneNumber();
current->info.getStatus();
outFile << current->info.getFirstName() << " "
<< current->info.getLastName() << endl;
outFile << month << " " << day << " " << year << endl;
outFile << street << endl << city << endl << state << endl << zip
<< endl;
outFile << current->info.getPhoneNumber() << endl
<< current->info.getStatus() << endl;
current = current->link;
}
}
addressBookType::addressBookType()
{
}
these are the two headers file that i suspect that has a problem with it but they have NO ERRORS at all
#include <iostream>
#include "linkedList.h"
using namespace std;
class orderedLinkedListType: public linkedListType
{
public:
bool search(const int& searchItem) const;
//Function to determine whether searchItem is in the list
//Postcondition: Returns true if searchItem is in the list;
// otherwise, the value false is returned.
void insertNode(const int& newItem);
//Function to insert newItem in the list
//Postcondition: first points to the new list and
// newItem is inserted at the proper place in the list
void deleteNode(const int& deleteItem);
//Function to delete deleteItem from the list
//Postcondition: If found, then the node containing the
// deleteItem is deleted from the list;
// first points to the first node of
// the new list
// If deleteItem is not in the list,
// an appropriate message is printed
void printListReverse() const;
//This function prints the list in reverse order
//Because the original list is in ascending order, the
//elements will be printed in descending order
private:
void reversePrint(nodeType *current) const;
//This function is called by the public member
//function to print the list in reverse order
};
bool orderedLinkedListType::search(const int& searchItem) const
{
bool found = false;
nodeType *current; //pointer to traverse the list
current = first; //start the search at the first node
while (current != NULL && !found)
if (current->info >= searchItem)
found = true;
else
current = current->link;
if (found)
found = (current->info == searchItem); //test for equality
return found;
}//end search
void orderedLinkedListType::insertNode(const int& newitem)
{
nodeType *current; //pointer to traverse the list
nodeType *trailCurrent; //pointer just before current
nodeType *newNode; //pointer to create a node
bool found;
newNode = new nodeType; //create the node
assert(newNode != NULL);
newNode->info = newitem; //store newitem in the node
newNode->link = NULL; //set the link field of the node
//to NULL
if (first == NULL) //Case 1
{
first = newNode;
count++;
}
else
{
current = first;
found = false;
while (current != NULL && !found) //search the list
if (current->info >= newitem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
if (current == first) //Case 2
{
newNode->link = first;
first = newNode;
count++;
}
else //Case 3
{
trailCurrent->link = newNode;
newNode->link = current;
count++;
}
}//end else
}//end insertNode
void orderedLinkedListType::deleteNode(const int& deleteItem)
{
nodeType *current; //pointer to traverse the list
nodeType *trailCurrent; //pointer just before current
bool found;
if (first == NULL) //Case 1
cout << "Cannot delete from an empty list." << endl;
else
{
current = first;
found = false;
while (current != NULL && !found) //search the list
if (current->info >= deleteItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
if (current == NULL) //Case 4
cout << "The item to be deleted is not in the "
<< "list." << endl;
else
if (current->info == deleteItem) //item to be
//deleted is in the list
{
if (first == current) //Case 2
{
first = first->link;
delete current;
}
else //Case 3
{
trailCurrent->link = current->link;
delete current;
}
count--;
}
else //Case 4
cout << "Item to be deleted is not in the "
<< "list." << endl;
}
} //end deleteNode
void orderedLinkedListType::reversePrint
(nodeType *current) const
{
if (current != NULL)
{
reversePrint(current->link); //print the tail
cout << current->info << " "; //print the node
}
}
void orderedLinkedListType::printListReverse() const
{
reversePrint(first);
cout << endl;
}
this is the second one:
#include <iostream>
#include <cassert>
#include <assert.h>
using namespace std;
//Definition of the node
struct nodeType
{
int info;
nodeType *link;
};
class linkedListType
{
public:
const linkedListType& operator=
(const linkedListType&);
//Overload the assignment operator.
void initializeList();
//Initialize the list to an empty state.
//Postcondition: first = NULL, last = NULL, count = 0;
bool isEmptyList() const;
//Function to determine whether the list is empty.
//Postcondition: Returns true if the list is empty,
// otherwise it returns false.
void print() const;
//Function to output the data contained in each node.
//Postcondition: none
int length() const;
//Function to return the number of nodes in the list.
//Postcondition: The value of count is returned.
void destroyList();
//Function to delete all the nodes from the list.
//Postcondition: first = NULL, last = NULL, count = 0;
int front() const;
//Function to return the first element of the list.
//Precondition: The list must exist and must not be
// empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the first
// element of the list is returned.
int back()const;
//Function to return the last element of the list.
//Precondition: The list must exist and must not be
// empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the last
// element of the list is returned.
bool search(const int& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the
// list, otherwise the value false is
// returned.
void insertFirst(const int& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list,
// last points to the last node in the list,
// and count is incremented by 1.
void insertLast(const int& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem
// is inserted at the end of the list,
// last points to the last node in the list,
// and count is incremented by 1.
void deleteNode(const int& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the list.
// first points to the first node, last
// points to the last node of the updated
// list, and count is decremented by 1.
linkedListType();
//default constructor
//Initializes the list to an empty state.
//Postcondition: first = NULL, last = NULL, count = 0;
linkedListType(const linkedListType& otherList);
//copy constructor
~linkedListType();
//destructor
//Deletes all the nodes from the list.
//Postcondition: The list object is destroyed.
protected:
int count; //variable to store the number of
//elements in the list
nodeType *first; //pointer to the first node of the list
nodeType *last; //pointer to the last node of the list
private:
void copyList(const linkedListType& otherList);
//Function to make a copy of otherList.
//Postcondition: A copy of otherList is created and
// assigned to this list.
};
bool linkedListType::isEmptyList() const
{
return(first == NULL);
}
linkedListType::linkedListType() //default constructor
{
first = NULL;
last = NULL;
count = 0;
}
void linkedListType::destroyList()
{
nodeType *temp; //pointer to deallocate the memory
//occupied by the node
while (first != NULL) //while there are nodes in the list
{
temp = first; //set temp to the current node
first = first->link; //advance first to the next node
delete temp; //deallocate the memory occupied by temp
}
last = NULL; //initialize last to NULL; first has already
//been set to NULL by the while loop
count = 0;
}
void linkedListType::initializeList()
{
destroyList(); //if the list has any nodes, delete them
}
void linkedListType::print() const
{
nodeType *current; //pointer to traverse the list
current = first; //set current so that it points to
//the first node
while (current != NULL) //while more data to print
{
cout << current->info << " ";
current = current->link;
}
}//end print
int linkedListType::length() const
{
return count;
} //end length
int linkedListType::front() const
{
assert(last != NULL);
return first->info; //return the info of the first node
}//end front
int linkedListType::back() const
{
assert(last != NULL);
return last->info; //return the info of the first node
}//end back
bool linkedListType::search(const int& searchItem) const
{
nodeType *current; //pointer to traverse the list
bool found = false;
current = first; //set current to point to the first
//node in the list
while (current != NULL && !found) //search the list
if (current->info == searchItem) //searchItem is found
found = true;
else
current = current->link; //make current point to
//the next node
return found;
}//end search
void linkedListType::insertFirst(const int& newItem)
{
nodeType *newNode; //pointer to create the new node
newNode = new nodeType; //create the new node
assert(newNode != NULL); //if unable to allocate memory,
//terminate the program
newNode->info = newItem; //store the new item in the node
newNode->link = first; //insert newNode before first
first = newNode; //make first point to the
//actual first node
count++; //increment count
if (last == NULL) //if the list was empty, newNode is also
//the last node in the list
last = newNode;
}//end insertFirst
void linkedListType::insertLast(const int& newItem)
{
nodeType *newNode; //pointer to create the new node
newNode = new nodeType; //create the new node
assert(newNode != NULL); //if unable to allocate memory,
//terminate the program
newNode->info = newItem; //store the new item in the node
newNode->link = NULL; //set the link field of newNode
//to NULL
if (first == NULL) //if the list is empty, newNode is
//both the first and last node
{
first = newNode;
last = newNode;
count++; //increment count
}
else //the list is not empty, insert newNode after last
{
last->link = newNode; //insert newNode after last
last = newNode; //make last point to the actual last node
count++; //increment count
}
}//end insertLast
void linkedListType::deleteNode(const int& deleteItem)
{
nodeType *current; //pointer to traverse the list
nodeType *trailCurrent; //pointer just before current
bool found;
if (first == NULL) //Case 1; the list is empty.
cout << "Cannot delete from an empty list."
<< endl;
else
{
if (first->info == deleteItem) //Case 2
{
current = first;
first = first->link;
count--;
if (first == NULL) //the list has only one node
last = NULL;
delete current;
}
else //search the list for the node with the given info
{
found = false;
trailCurrent = first; //set trailCurrent to point
//to the first node
current = first->link; //set current to point to
//the second node
while (current != NULL && !found)
{
if (current->info != deleteItem)
{
trailCurrent = current;
current = current-> link;
}
else
found = true;
}//end while
if (found) //Case 3; if found, delete the node
{
trailCurrent->link = current->link;
count--;
if (last == current) //node to be deleted
//was the last node
last = trailCurrent; //update the value
//of last
delete current; //delete the node from the list
}
else
cout << "The item to be deleted is not in "
<< "the list." << endl;
}//end else
}//end else
}//end deleteNode
void linkedListType::copyList
(const linkedListType& otherList)
{
nodeType *newNode; //pointer to create a node
nodeType *current; //pointer to traverse the list
if (first != NULL) //if the list is nonempty, make it empty
destroyList();
if (otherList.first == NULL) //otherList is empty
{
first = NULL;
last = NULL;
count = 0;
}
else
{
current = otherList.first; //current points to the
//list to be copied
count = otherList.count;
//copy the first node
first = new nodeType; //create the node
assert(first != NULL);
first->info = current->info; //copy the info
first->link = NULL; //set the link field of
//the node to NULL
last = first; //make last point to the
//first node
current = current->link; //make current point to
//the next node
//copy the remaining list
while (current != NULL)
{
newNode = new nodeType; //create a node
assert(newNode != NULL);
newNode->info = current->info; //copy the info
newNode->link = NULL; //set the link of
//newNode to NULL
last->link = newNode; //attach newNode after last
last = newNode; //make last point to
//the actual last node
current = current->link; //make current point
//to the next node
}//end while
}//end else
}//end copyList
linkedListType::~linkedListType() //destructor
{
destroyList();
}//end destructor
linkedListType::linkedListType
(const linkedListType& otherList)
{
first = NULL;
copyList(otherList);
}//end copy constructor
//overload the assignment operator
const linkedListType& linkedListType::operator=
(const linkedListType& otherList)
{
if (this != &otherList) //avoid self-copy
{
copyList(otherList);
}//end else
return *this;
}
i got an error saying error: request for member 'printInfo' in 'current->nodeType::info', which is of non-class type 'int'. There are few more headers file linking to this header, which all have template coding. However i managed to remove template coding from all the other headers with no errors at all with the exception of this header. can anyone tell me how to solve it?
You defined struct nodeType with member int info;. But in addressBookType::printInfoOf (and addressBookType::print) you have the line location->info.printInfo();
Since info is an int, it has no methods to call, printInfo or otherwise, thus the error.
It looks like the problem is a result of another type mismatch in your code. addressBookType's insertNode takes a const extPersonType& (which I assume is defined elsewhere and implements the methods you're trying to use?), but passes it to orderedLinkedListType::insertNode, which takes and stores const int&. This normally wouldn't work, but at a guess, extPersonType is a type (possibly a C++11 strongly-typed enum) that has an implicit conversion to int, which might avoid compile errors during assignment, but still effectively strips all the extPersonType-specific behaviors on insertNode, it goes from extPersonType to just an int.
If you want a general purpose linked list, you need to template it to work with more than just int, e.g. changing nodeType to:
template<typename T>
struct nodeType {
T info;
nodeType<T> *link;
};
and updating all the methods associated with nodeType and the orderedLinkedListType to template as appropriate to the specific type, rather than int. If you're being lazy, you could instead just change all uses of int in nodeType and orderedLinkedListType to extPersonType, but now the code is no good for ints, so pick your poison.
Hi right now I am trying to rewrite my code so it can take in each item of the linked list as a string reading a first and last name. At the moment I got the program to work, but when I enter a first and last name the program treats them as separate elements instead of one single entity. So basically I want "Jack Frost" to have a linked list length of 1 instead 2, and then I try to prompt the user to enter a first and last name so they are deleted from the list. Hopefully someone can help. I am posting the tester program I made and the header file. Fair warning the header file is a bit long. The tester program needs to print the full list line by line with first and last name.
Update: I do prompt the user to enter first and last name in the same line. They are for some reason being counted as two separate elements, I need to them to be considered on element together.
#ifndef H_LinkedListType
#define H_LinkedListType
#include <iostream>
//Definition of the node
template <typename Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template<typename Type>
class linkedListType
{
public:
const linkedListType<Type>& operator=(const linkedListType<Type>&);
//Overload the assignment operator
void initializeList();
//Initialize the list to an empty state
//Post: first = NULL, last = NULL
bool isEmptyList();
//Function returns true if the list is empty;
//otherwise, it returns false
bool isFullList();
//Function returns true if the list is full;
//otherwise, it returns false
void print();
//Output the data contained in each node
//Pre: List must exist
//Post: None
int length();
//Return the number of elements in the list
void destroyList();
//Delete all nodes from the list
//Post: first = NULL, last = NULL
void retrieveFirst(Type& firstElement);
//Return the info contained in the first node of the list
//Post: firstElement = first element of the list
void search(const Type& searchItem);
//Outputs "Item is found in the list" if searchItem is in
//the list; otherwise, outputs "Item is not in the list"
void insertFirst(const Type& newItem);
//newItem is inserted in the list
//Post: first points to the new list and the
// newItem inserted at the beginning of the list
void insertLast(const Type& newItem);
//newItem is inserted in the list
//Post: first points to the new list and the
// newItem is inserted at the end of the list
// last points to the last node in the list
void deleteNode(const Type& deleteItem);
//if found, the node containing deleteItem is deleted
//from the list
//Post: first points to the first node and
// last points to the last node of the updated list
linkedListType();
//default constructor
//Initializes the list to an empty state
//Post: first = NULL, last = NULL
linkedListType(const linkedListType<Type>& otherList);
//copy constructor
~linkedListType();
//destructor
//Deletes all nodes from the list
//Post: list object is destroyed
protected:
nodeType<Type> *first; //pointer to the first node of the list
nodeType<Type> *last; //pointer to the last node of the list
};
template<typename Type>
void linkedListType<Type>::initializeList()
{
destroyList(); //if the list has any nodes, delete them
}
template<typename Type>
void linkedListType<Type>::print()
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current so that it points to
//the first node
while(current != NULL) //while more data to print
{
cout<<current->info<<" ";
current = current->link;
}
} //end print
template<typename Type>
int linkedListType<Type>::length()
{
int count = 0;
nodeType<Type> *current; //pointer to traverse the list
current = first;
while (current!= NULL)
{
count++;
current = current->link;
}
return count;
} // end length
template<typename Type>
void linkedListType<Type>::search(const Type& item)
{
nodeType<Type> *current; //pointer to traverse the list
bool found;
if(first == NULL) //list is empty
cout<<"Cannot search an empty list. "<<endl;
else
{
current = first; //set current pointing to the first
//node in the list
found = false; //set found to false
while(!found && current != NULL) //search the list
if(current->info == item) //item is found
found = true;
else
current = current->link; //make current point to
//the next node
if(found)
cout<<"Item is found in the list."<<endl;
else
cout<<"Item is not in the list."<<endl;
} //end else
} //end search
template<typename Type>
void linkedListType<Type>::insertLast(const Type& newItem)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = NULL; //set the link field of new node
//to NULL
if(first == NULL) //if the list is empty, newNode is
//both the first and last node
{
first = newNode;
last = newNode;
}
else //if the list is not empty, insert newNnode after last
{
last->link = newNode; //insert newNode after last
last = newNode; //make last point to the actual last node
}
} //end insertLast
template<typename Type>
void linkedListType<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if(first == NULL) //Case 1; list is empty.
cout<<"Can not delete from an empty list.\n";
else
{
if(first->info == deleteItem) //Case 2
{
current = first;
first = first ->link;
if(first == NULL) //list had only one node
last = NULL;
delete current;
}
else //search the list for the node with the given info
{
found = false;
trailCurrent = first; //set trailCurrent to point to
//the first node
current = first->link; //set current to point to the
//second node
while((!found) && (current != NULL))
{
if(current->info != deleteItem)
{
trailCurrent = current;
current = current-> link;
}
else
found = true;
} // end while
if(found) //Case 3; if found, delete the node
{
trailCurrent->link = current->link;
if(last == current) //node to be deleted was
//the last node
last = trailCurrent; //update the value of last
delete current; //delete the node from the list
}
else
cout<<"Item to be deleted is not in the list."<<endl;
} //end else
} //end else
} //end deleteNode
#endif
This is the tester program below.
//This program tests various operation of a linked list
#include "stdafx.h"
#include <string>//Need to import string to the class to be able to use that type
#include <iostream>
#include "linkedList.h"
using namespace std;
int main()
{
linkedListType<string> list1, list2;
int num;
string name;//Input from the user
//cout<<"Enter numbers ending with -999"
//<<endl;
//cin>>num;
cout<<"Please enter first and last name in each line, enter end to close program" //Prompting the user to enter first and last name on each line til they specify "end"
<<endl;
cin>>name;
while(name != "end")//Checks if user entered name if not it will proceed to keep prompting the user
{
list1.insertLast(name);//inserts the name at the end of the list
cin>>name;
}
cout<<endl;
cout<<"List 1: ";
list1.print();//Prints all the names line by line
cout<<endl;
cout<<"Length List 1: "<<list1.length()//Gives length of how many names are in the list
<<endl;
list2 = list1; //test the assignment operator
cout<<"List 2: ";
list2.print();
cout<<endl;
cout<< "Length List 2: "<< list2.length() <<endl;
cout<< "Enter the name to be " << "deleted: ";
cin>>num;
cout<<endl;
list2.deleteNode(name);
cout<<"After deleting the node, "
<< "List 2: "<<endl;
list2.print();
cout<<endl;
cout<<"Length List 2: "<<list2.length()
<<endl;
system("pause");
return 0;
cin input is separated also with space, in your sample code, in the last loop when read cin>>name; name would take value for all spaces and new line separated words.
Use this instead:
std::string name;
std::getline(std::cin, name);
The easiest solution is to create a structure containing your two strings:
struct Person_Name
{
std::string first;
std::string last;
};
Then you can "pass" the structure as the type in your linked list:
LinkedListType<Person_Name> people;
You may have to adjust the "genericity" or assumptions made by the list or add functionality to the Person_Name to make it conform to the list's interface.
Edit 1: Comparing the data
The linked list is probably using operator< to order the nodes in the list. So you will have to add that overloaded operator to your structure:
struct Person_Name
{
std::string first_name;
std::string second_name;
bool operator<(const& Person_Name pn) const
{
if (second_name == pn.second_name)
{
return first_name < pn.first_name;
}
return second_name < pn.second_name;
}
};
You can implement operator== in a similar fashion.
Instead of name and surname in two lines get them in one line as following:
char name[256]
std::cout << "Please, enter your name: and surname";
std::cin.getline (name,256);
To split name and surname copy/paste this code to your solution.
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
Then divide name and surname you will write
vector<string> person = split(name, ' ');
person.at(0) // the name of the person
person.at(1) //the surname of the person
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why can templates only be implemented in the header file?
What is an undefined reference/unresolved external symbol error and how do I fix it?
Again this is a homework assignment and my instructor has given us plenty of feedback but I am still at a lost for this compile issue.
When I place the main function inside the implementation file the program compiles and works perfectly. However when I place the main function into main.cpp the compiler complains:
unresolved external symbol "public: __thiscall doublyLinkedList<int>::doublyLinkedList<int>(void)" (??0?$doublyLinkedList#H##QAE#XZ) referenced in function
Header File
#ifndef H_doublyLinkedList
#define H_doublyLinkedList
#include <iostream>
#include <cassert>
using namespace std;
//Definition of the node
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *next;
nodeType<Type> *back;
};
template <class Type>
class doublyLinkedList
{
public:
const doublyLinkedList<Type>& operator=
(const doublyLinkedList<Type> &);
//Overload the assignment operator.
void initializeList();
//Function to initialize the list to an empty state.
//Postcondition: first = NULL; last = NULL; count = 0;
bool isEmptyList() const;
//Function to determine whether the list is empty.
//Postcondition: Returns true if the list is empty,
// otherwise returns false.
void destroy();
//Function to delete all the nodes from the list.
//Postcondition: first = NULL; last = NULL; count = 0;
void print() const;
//Function to output the info contained in each node.
void reversePrint() const;
//Function to output the info contained in each node
//in reverse order.
int length() const;
//Function to return the number of nodes in the list.
//Postcondition: The value of count is returned.
Type front() const;
//Function to return the first element of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the first
// element of the list is returned.
Type back() const;
//Function to return the last element of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the last
// element of the list is returned.
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is found in
// the list, otherwise returns false.
void insert(const Type& insertItem);
//Function to insert insertItem in the list.
//Precondition: If the list is nonempty, it must be in
// order.
//Postcondition: insertItem is inserted at the proper place
// in the list, first points to the first
// node, last points to the last node of the
// new list, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing deleteItem
// is deleted from the list; first points
// to the first node of the new list, last
// points to the last node of the new list,
// and count is decremented by 1; otherwise,
// an appropriate message is printed.
doublyLinkedList();
//default constructor
//Initializes the list to an empty state.
//Postcondition: first = NULL; last = NULL; count = 0;
doublyLinkedList(const doublyLinkedList<Type>& otherList);
//copy constructor
~doublyLinkedList();
//destructor
//Postcondition: The list object is destroyed.
public:
int count;
nodeType<Type> *first; //pointer to the first node
nodeType<Type> *last; //pointer to the last node
public:
void copyList(const doublyLinkedList<Type>& otherList);
//Function to make a copy of otherList.
//Postcondition: A copy of otherList is created and
// assigned to this list.
};
#endif
Implementation file:
#include <iostream>
#include <cassert>
#include "doublyLinkedList.h"
using namespace std;
template <class Type>
doublyLinkedList<Type>::doublyLinkedList()
{
first= NULL;
last = NULL;
count = 0;
}
template <class Type>
bool doublyLinkedList<Type>::isEmptyList() const
{
return (first == NULL);
}
template <class Type>
void doublyLinkedList<Type>::destroy()
{
nodeType<Type> *temp; //pointer to delete the node
while (first != NULL)
{
temp = first;
first = first->next;
delete temp;
}
last = NULL;
count = 0;
}
template <class Type>
void doublyLinkedList<Type>::initializeList()
{
destroy();
}
template <class Type>
int doublyLinkedList<Type>::length() const
{
return count;
}
template <class Type>
void doublyLinkedList<Type>::print() const
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current to point to the first node
while (current != NULL)
{
cout << current->info << " "; //output info
current = current->next;
}//end while
}//end print
template <class Type>
void doublyLinkedList<Type>::reversePrint() const
{
nodeType<Type> *current; //pointer to traverse
//the list
current = last; //set current to point to the
//last node
while (current != NULL)
{
cout << current->info << " ";
current = current->back;
}//end while
}//end reversePrint
template <class Type>
bool doublyLinkedList<Type>::
search(const Type& searchItem) const
{
bool found = false;
nodeType<Type> *current; //pointer to traverse the list
current = first;
while (current != NULL && !found)
if (current->info >= searchItem)
found = true;
else
current = current->next;
if (found)
found = (current->info == searchItem); //test for
//equality
return found;
}//end search
template <class Type>
Type doublyLinkedList<Type>::front() const
{
assert(first != NULL);
return first->info;
}
template <class Type>
Type doublyLinkedList<Type>::back() const
{
assert(last != NULL);
return last->info;
}
template <class Type>
void doublyLinkedList<Type>::insert(const Type& insertItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
nodeType<Type> *newNode; //pointer to create a node
bool found;
newNode = new nodeType<Type>; //create the node
newNode->info = insertItem; //store the new item in the node
newNode->next = NULL;
newNode->back = NULL;
if(first == NULL) //if the list is empty, newNode is
//the only node
{
first = newNode;
last = newNode;
count++;
}
else
{
found = false;
current = first;
while (current != NULL && !found) //search the list
if (current->info >= insertItem)
found = true;
else
{
trailCurrent = current;
current = current->next;
}
if (current == first) //insert newNode before first
{
first->back = newNode;
newNode->next = first;
first = newNode;
count++;
}
else
{
//insert newNode between trailCurrent and current
if (current != NULL)
{
trailCurrent->next = newNode;
newNode->back = trailCurrent;
newNode->next = current;
current->back = newNode;
}
else
{
trailCurrent->next = newNode;
newNode->back = trailCurrent;
last = newNode;
}
count++;
}//end else
}//end else
}//end insert
template <class Type>
void doublyLinkedList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if (first == NULL)
cout << "Cannot delete from an empty list." << endl;
else if (first->info == deleteItem) //node to be deleted is
//the first node
{
current = first;
first = first->next;
if (first != NULL)
first->back = NULL;
else
last = NULL;
count--;
delete current;
}
else
{
found = false;
current = first;
while (current != NULL && !found) //search the list
if (current->info >= deleteItem)
found = true;
else
current = current->next;
if (current == NULL)
cout << "The item to be deleted is not in "
<< "the list." << endl;
else if (current->info == deleteItem) //check for
//equality
{
trailCurrent = current->back;
trailCurrent->next = current->next;
if (current->next != NULL)
current->next->back = trailCurrent;
if (current == last)
last = trailCurrent;
count--;
delete current;
}
else
cout << "The item to be deleted is not in list."
<< endl;
}//end else
}//end deleteNode
template <class Type>
void doublyLinkedList<Type>::copyList(const doublyLinkedList<Type>& otherList)
{
//cout << "The definition of this function is left as an exercise." << endl;
//cout << "See Programming Execrise 9." << endl;
template <class Type>
doublyLinkedList<Type>::doublyLinkedList(const doublyLinkedList<Type>& otherList)
{
// cout << "The definition of the copy constructor is left as an exercise." << endl;
// cout << "See Programming Execrise 9." << endl;
}
template <class Type>
const doublyLinkedList<Type>& doublyLinkedList<Type>::operator=
(const doublyLinkedList<Type> &)
// cout << "Overloading the assignment operator is left as an exercise." << endl;
// cout << "See Programming Execrise 9." << endl;
}
template <class Type>
doublyLinkedList<Type>::~doublyLinkedList()
{
//cout << "Definition of the destructor is left as an exercise." << endl;
//cout << "See Programming Execrise 9." << endl;
}
Main Function:
//Program to test various operations on a doubly linked list
#include <iostream>
#include "doublyLinkedList.h"
using namespace std;
int main()
{
char choice;
int n = 0;
doublyLinkedList<int> myList;
cout<<"this is a test"<<endl;
do {
cout<<"Main Menu:"<<endl;
cout<<"Choice of operations to perform on Dobule Linked List"<<endl;
cout<<"Create list values : C"<<endl;
cout<<"Initialize List: Z"<<endl;
cout<<"Check List Empty: M"<<endl;
cout<<"Destroy List: E "<<endl;
cout<<"Print List : P"<<endl;
cout<<"Reverse printed list: R"<<endl;
cout<<"Length of List: L"<<endl;
cout <<"Front of List: F"<<endl;
cout<<"Back of List: B"<<endl;
cout<<"Search list: S"<<endl;
cout<<"Insert List: I"<<endl;
cout<<"delete list: D"<<endl;
cout<<"use copy constructor : U" <<endl;
cout <<"quit: Q"<<endl;
cin >> choice;
if ((choice == 'I' )|| (choice =='D')|| (choice == 'S'))
{
cout<<"Enter value to manipulate: "<<endl;
cin >> n;
}
switch ( choice)
{
case 'C':
cout<<"Please enter a list"<<endl;
while(n!= -999){
myList.insert(n);
cin>>n;}
break;
case 'S': if (myList.search(n))
cout<< " List contains: "<<n<<endl;
else
cout<<"List does not contain "<<n<<endl;
break;
case 'I':
myList.insert(n);
cout<<"element was inserted"<<endl;
break;
case 'D':
myList.deleteNode(n);
cout<<"node was deleted"<<endl;
break;
case 'L': cout<<"Length is \n"<<endl;
myList.length();
break;
case 'B':
cout<<"back element is : "<< myList.back();
break;
case 'F' :
cout<<"front element is "<<myList.front();
break;
case 'Z' : myList.initializeList();
cout<<"list initialized"<<endl;
case 'M': if (myList.isEmptyList())
cout<<"is empty"<< endl;
else
cout<<"is not empty"<<endl;
break;
case 'E': myList.destroy();
cout<<"list destroyed"<<endl;
break;
case 'P': myList.print();
break;
case'R': cout<<"reversed"<<endl;
myList.reversePrint();
break;
}
}while(choice!= 'Q');
return 0;
}
I am looking for guidance. I know the answer is really simple and I am just not seeing it. I thought about using the keyword extern but am not sure really how to use it. Like I said in the tags this is homework so I am not looking for a quick fix I am looking to learn from my mistakes.
I really appreciate this site and all the members.
All the code i posted on here was available for free by the book publisher, I have left out my original code except for main.cpp
You need to move your implementation into the header file. Unlike normal functions the compiler needs to be able to see all of the template code at the point of use.
See the answers in this question for more information:
Why can templates only be implemented in the header file?
The problem is that you don't have the template definitions available in your main compilation unit (where they are used).
This means you need to have explicit instantiations for the types it is used with.
Add
template class doublyLinkedList<int>;
to the end of doublyLinkedList.cpp to explicitely instantiate it.
Or include the cpp in the header,
or directly into main.cpp