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
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.
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).
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.
So I've been searching forums, but im still very new to the language and linked lists so I can barely decipher the results.
basically I made a delete function for my linked list.
I can currently Create a list, traverse the list, sort the list, search the list, and insert before any node in the linked list. I recycled some code from the insert to locate the point in the list where I could delete. My main point of confusion is how to link the previous points to the node that is after the one I am deleting.
I won't write a whole new linked list implementation but i can point out some of the problems with the code for you.
The trick is to stay one node ahead of the one you want to delete.
I have renamed entry to current for clarity
nodetype *current , *first, *next;
int akey;
// With this line your search will start from the second element.
// current =start->ptr;
// Should be
current = start;
// this is not needed. I am assuming the last node has NULL value for '->ptr'
// last=start;
next = current->ptr;
cout<<"Input Data You Would Like To Delete"<<endl;
cin>>akey;
// Check if the first node contains the data
// Assuming the list will have at least one element. i.e. current is not NULL
while (current->adata == akey)
{
// Delete it.
delete current;
// Update current for the while loop
current = next;
// update next too.
next = current->ptr;
}
// Now we know the first element doesn't contain the data.
// Update the pointer to the begging of the new list if anything is removed from the top.
first = current;
// This has unnecessary checks.
// ****Specifically (akey!=current->adata) will
// prevent you from entering the loop if it is false.
// while((akey!=current->adata)&&(current->ptr !=NULL))
while(next != NULL) // This should be enough
{
if(next->adata == akey)
{
// make the current node (before the 'deletion point')
// lined to the one after the 'deletion point (next of the next)
current->ptr = next->ptr;
// delete the node.
delete next;
// Make the next pointer point to the new next.
next = current->ptr
}
// Otherwise advance both current and next.
else {
current = next;
next = next->ptr;
}
}
// Use this to test it.
current = first;
while(current){
cout<<current->adata<<", ";
current = current->ptr;
}
This is not the cleanest way. However it is similar to your implementation so you can see where you went wrong.
#include <iostream>
#include <string>
// blank line(s) after includes
using namespace std; // some people will say to avoid this
// but I use it in examples for brevity
// blank line(s) around class def
class nodetype
{ // bracket on its own line
public: // non indented visibility specifier
nodetype(int value, nodetype *p) // constructor first declared in class
{
adata = value; // level of indentation for fn body
ptr = p; // spaces around operators like =
}
// blank line(s) between fns and vars
int adata;
nodetype *ptr;
};
// blank line(s) between class and fn
void LinkedListDelete(nodetype **start, int akey)
{
nodetype *current, **previous; // pointer *s are connected to vars
// blank line between section
previous = start;
current = *start;
// blank line between section
// I use blank lines a lot, they help
// me to organize my thoughts
while((current != NULL) && (akey != current->adata))
{ // indentation inside nested scope
previous = ¤t->ptr; // no space for unary operators like &
current = current->ptr; // assignments justified to same level
}
if (current != NULL)
{
*previous = current->ptr; // no space for unary *, space for =
delete current;
}
// more blank lines between sections
return;
}
void LinkedListPrint(nodetype *list) // no space for unary *
{ // brackets on their own lines
while (list != NULL) // space around !=
{
cout << "(Node: " << list->adata << ") ";
list = list->ptr; // spaces around <<
}
cout << endl;
}
int main()
{
nodetype *node = new nodetype(5, new nodetype(10, // justified stuff
new nodetype(7, new nodetype(14,
new nodetype(23, NULL)))));
// blank lines
cout << "Build linked list: ";
LinkedListPrint(node);
cout << "Removed node 7: ";
LinkedListDelete(&node, 7);
LinkedListPrint(node);
return 0;
}
I made this code based on the code you provided. It's not quite the same, I changed some things, but it does what you want it to. I had to guess what the structure of nodetype was, and I added a constructor for my convenience. I added some comments pointing out aspects of my style.
Notice that it's easier to read than the code you originally provided. Style is important. People will tell you that you have to use X or Y style, but what really matters is that you pick whatever style you like and stick to it consistently; it will make it easier for you to read and understand your own code quickly.
Believe me you, when you've written a lot of code, you stop being able to remember all of it at once, and being able to figure out what you were doing quickly is essential.
Consider the structure given below,
struct info
{
int data;
struct info *next;
};
if you use the above structure to store records in your linked list, then the following code can be used to delete elements from your linked list,
void delitem()
{
info *curr,*prev;
int tdata;
if(head==NULL)
{
cout<<"\nNo Records to Delete!!!";
}
cout<<"\nEnter the Data to be deleted: ";
cin>>tdata;
prev=curr=head;
while((curr!=NULL)&&(curr->data!=tdata))
{
prev=curr;
curr=curr->next;
}
if(curr==NULL)
{
cout<<"\nRecord not Found!!!";
return;
}
if(curr==head)
{
head=head->next;
cout<<"\nData deleted: "<<tdata;
}
else
{
prev->next=curr->next;
if(curr->next==NULL)
{
temp=prev;
}
cout<<"\nData deleted: "<<tdata;
}
delete(curr);
}
I think it is too simple and easy to delete a node or insert ine in linked-list but it requires precise understanding of its MECHANISM. this example shows how to add and remove nodes however it is not a full program but it reveals the mechanism of adding and deleting and moving alinked-list:
#include <iostream>
using namespace std;
//class Data to store ages. in a real program this class can be any other
//class for example a student class or customer...
class Data
{
public:
Data(int age):itsAge(age){}
~Data(){}
void SetAge(int age){itsAge=age;}
int getAge()const{return itsAge;}
private:
int itsAge;
};
//the most important part of the program is the linked0list
class Node
{
public:
//we just make itsPtrHead when created points to Null even if we pass a pointer to Data that is not NULL
Node(Data* pData): itsPtrData(pData),itsPtrHead(NULL),itsCount(0){}
Data* getPdata()const;
Node* getPnext()const;
int getCount()const{return itsCount;}
void insertNode(Data*);//import bcause it shoes the mechanism of linked-list
void deleteNode(int);//most significant in this program
Data* findData(int&,int);
void print()const;
private:
Data* itsPtrData;
Node* itsPtrHead;
int itsCount;
};
Data* Node::getPdata()const
{
if(itsPtrData)
return itsPtrData;
else
return NULL;
}
Node* Node::getPnext()const
{
return itsPtrHead;
}
void Node::insertNode(Data* pData)
{
Node* pNode=new Node(pData);//create a node
Node* pCurrent=itsPtrHead;//current node which points first to the first node that is the "head bode"
Node* pNext=NULL;//the next node
int NewAge=pData->getAge();//the new age that is past to insertNode function
int NextAge=0;//next age
itsCount++;//incrementing the number of nodes
//first we check wether the head node "itsPtrHead" points NULL or not
//so if it is null then we assign it the new node "pNode" and return from insert function
if(!itsPtrHead)
{
itsPtrHead=pNode;
return;
}
//if the condition above fails (head is not null) then check its value and
//compare it with new age and if the new one is smaller than the head
//make this new one the head and then the original node that head points to it make it its next node to the head
if(itsPtrHead->getPdata()->getAge() > NewAge)
{
pNode->itsPtrHead=itsPtrHead;
itsPtrHead=pNode;
//exit the function
return;
}
//if the condition above fails than we move to the next node and so on
for(;;)
{
//if the next node to the current node is null the we set it with this new node(pNode) and exit
if(!pCurrent->itsPtrHead)
{
pCurrent->itsPtrHead=pNode;
return;
}
//else if it not null(next node to current node)
//then we compare the next node and new node
pNext=pCurrent->itsPtrHead;
NextAge=pNext->getPdata()->getAge();
//if next node's age is greater than new then we want new node
//to be the next node to current node then make the original next to current to be the next to its next
if(NextAge > NewAge)
{
pCurrent->itsPtrHead=pNode;
pNode->itsPtrHead=pNext;
//exitting
return;
}
//if no condition succeeds above then move to next node and continue until last node
pCurrent=pNext;
}
}
// delete a node is a bit different from inserting a node
void Node::deleteNode(int age)
{
//deleting a node is much like adding one the differecne is a bit trickier
Node* pTmp=itsPtrHead;
Node* pCurrent=itsPtrHead;
Node* pNext=NULL;
//1 checking for wether age (node contains age) to be deleted does exist
for(;pTmp;pTmp=pTmp->itsPtrHead)
{
if(pTmp->getPdata()->getAge() == age)
break;
}
//if age to be deleted doesn't exist pop up a message and return
if(!pTmp)
{
cout<<age<<": Can't be found!\n";
return;
}
int NextAge=0;
for(;;)
{
//if age to be deleted is on the head node
if(itsPtrHead->getPdata()->getAge() == age)
{
//store the next to head node
pTmp=itsPtrHead->itsPtrHead;
//delete head node
delete itsPtrHead;
//assign the head new node (node after the original head)
itsPtrHead=pTmp;
//decrement the count of nodes
itsCount--;
//exiting gracefully
return;
}
//moving to next node
pNext=pCurrent->itsPtrHead;
NextAge=pNext->getPdata()->getAge();
//checking next node age with age to be deleted. if they
//match delete the next node
if(NextAge == age)
{
//next node holds the target age so we want its NEXT node
//and store it in pTmp;
pTmp=pNext->itsPtrHead;//Next node of the target node
//pCurrent doesn't yet hold the target age but it is the
//previous node to target node
//change the next node of pCurrent so that it doesn't
//point to the target node but instead to the node right
//after it
pCurrent->itsPtrHead=pTmp;
//delete the target node (holds the target age)
delete pNext;
//decrement number of nodes
itsCount--;
//exit
return;
}
//if pNext doesn't point to target node move to the next node
//by making pCurrent points to the next node in the list
pCurrent=pNext;
}
}
void Node::print()const
{
Node* pTmp=itsPtrHead;
while(pTmp)
{
cout<<"age: "<<pTmp->getPdata()->getAge()<<endl;
pTmp=pTmp->itsPtrHead;
}
}
int main()
{
//note this is not a real proram just we show how things works
Data* pData=new Data(6);
Node theNode(pData);
theNode.print();
pData=new Data(19);
theNode.insertNode(pData);
pData=new Data(20);
theNode.insertNode(pData);
pData=new Data(23);
theNode.insertNode(pData);
pData=new Data(25);
theNode.insertNode(pData);
pData=new Data(30);
theNode.insertNode(pData);
pData=new Data(27);
theNode.insertNode(pData);
pData=new Data(33);
theNode.insertNode(pData);
pData=new Data(18);
theNode.insertNode(pData);
theNode.print();
cout<<endl<<endl;
//int age;
//int index;
//cout<<"Age to finde: ";
//cin>>age;
//cout<<endl;
//theNode.Find(index,age);
//cout<<age<<" : Found on index: "<<index<<endl;
//theNode.modify(age);
//theNode.print();
int age;
cout<<"age to delete: ";
cin>>age;
cout<<endl;
theNode.deleteNode(age);
theNode.print();
cout<<endl<<endl<<endl;
return 0;
}
//modify and other member functions are not the purpose of this program
void Delete()
{
int num;
cout<<"enter node to delete"<<endl;
cin>>num;
node *nodeptr=head;
node *prev;
if(head==0)
{
cout<<"list is empty"<<endl;
}
else if(head->data==num)
{
node *t=head;
head=head->next;
delete t;
}
else
{
nodeptr=head;
prev=head;
while(nodeptr!=NULL)
{
if(nodeptr->data==num)
{
prev->next=nodeptr->next;
node *tem=nodeptr->next;
delete tem;
}
prev=nodeptr;
nodeptr=nodeptr->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