SlideShare a Scribd company logo
#ifndef LINKED_LIST_
#define LINKED_LIST_
template
class LinkedList {
private:
std::shared_ptr> headPtr; // Pointer to first node in the chain;
// (contains the first entry in the list)
int itemCount; // Current count of list items
std::shared_ptr> getNodeAt(int position) const;
public:
LinkedList();
LinkedList(const LinkedList& aList);
virtual ~LinkedList();
bool isEmpty() const;
int getLength() const;
bool insert(int newPosition, const ItemType& newEntry);
bool remove(int position);
void clear();
/** throw PrecondViolatedExcept if position < 1 or
position > getLength(). */
ItemType getEntry(int position) const throw(PrecondViolatedExcept);
/** throw PrecondViolatedExcept if position < 1 or
position > getLength(). */
void replace(int position, const ItemType& newEntry)
throw(PrecondViolatedExcept);
// Operator Overloading
void operator = (const LinkedList& arg);
friend std::ostream& operator << (std::ostream& os, const LinkedList& arg)
{
os << "There are " << arg.getLength() << " values in the list:" << std::endl;
for (int i{ 1 }; i <= arg.getLength(); i++) {
os << arg.getEntry(i) << std::endl;
}
os << std::endl << std::endl << std::endl << std::endl;
return os;
}
};
// Returns a pointer to the Node at the given position.
template
std::shared_ptr> LinkedList::getNodeAt (int position) const {
std::shared_ptr> currPtr{ headPtr };
for (int i{ 1 }; i < position; i++)
currPtr = currPtr->getNext();
return currPtr;
}
// Default constructor.
template
LinkedList::LinkedList() {
headPtr = nullptr;
itemCount = 0;
}
// Copy constructor.
template
LinkedList::LinkedList(const LinkedList& aList) {
itemCount = aList.getLength();
auto currPtr{ aList.headPtr };
auto newNodePtr{ headPtr = std::make_shared>(currPtr->getItem()) };
auto prevNodePtr{ newNodePtr };
currPtr = currPtr->getNext();
for (int i{ 2 }; i <= itemCount; i++) {
newNodePtr = std::make_shared>(currPtr->getItem());
prevNodePtr->setNext(newNodePtr);
prevNodePtr = newNodePtr;
currPtr = currPtr->getNext();
}
}
// Destructor.
template
LinkedList::~LinkedList() {
headPtr = nullptr;
itemCount = 0;
}
// Accessor/Info Functions.
template
bool LinkedList::isEmpty() const {
return (itemCount > 0)?0:1;
}
template
int LinkedList::getLength() const {
return itemCount;
}
// Places a Node at a given position (element at the same position is now pos+1).
template
bool LinkedList::insert(const int newPosition,
const ItemType& newEntry)
{
bool ableToInsert{ (newPosition >= 1) &&
(newPosition <= itemCount + 1) };
if (ableToInsert)
{
// Create a new node containing the new entry
auto newNodePtr{ std::make_shared>(newEntry) };
// Attach new node to chain
if (newPosition == 1)
{
// Insert new node at beginning of chain
newNodePtr->setNext(headPtr);
headPtr = newNodePtr;
}
else
{
// Find node that will be before new node
auto prevPtr{ getNodeAt(newPosition - 1) };
// Insert new node after node to which prevPtr points
newNodePtr->setNext(prevPtr->getNext());
prevPtr->setNext(newNodePtr);
} // end if
itemCount++; // Increase count of entries
} // end if
return ableToInsert;
} // end insert
// Removes the Node at the given position.
template
bool LinkedList::remove(const int position)
{
bool ableToRemove = (position >= 1) && (position <= itemCount);
if (ableToRemove)
{
if (position == 1)
{
// Remove the first node in the chain
headPtr = headPtr->getNext();
}
else
{
// Find node that is before the one to delete
auto prevPtr{ getNodeAt(position - 1) };
// Point to node to delete
auto curPtr{ prevPtr->getNext() };
// Disconnect indicated node from chain by connecting the
// prior node with the one after
prevPtr->setNext(curPtr->getNext());
} // end if
itemCount--; // Decrease count of entries
} // end if
return ableToRemove;
} // end remove
// Replaces the Entry in the given Node with the new Entry.
template
void LinkedList::replace(const int position, const ItemType& newEntry)
throw(PrecondViolatedExcept)
{
if (position > this->getLength() || position < 1)
throw PrecondViolatedExcept("replace() called with a position out of bounds.");
else
getNodeAt(position)->setItem(newEntry);
}
template
void LinkedList::clear()
{
headPtr = nullptr;
itemCount = 0;
} // end clear
template
ItemType LinkedList::getEntry(int position) const throw(PrecondViolatedExcept)
{
if (position > this->getLength() || position < 1)
throw PrecondViolatedExcept("getEntry() called with a position out of bounds.");
else
return getNodeAt(position)->getItem();
}
// Makes the calling Linked List's entries the same as the given Linked List.
template
void LinkedList::operator = (const LinkedList& arg) {
if (arg.isEmpty())
return;
// First section copies the given list into the calling list's existing nodes.
bool isThisLarger{ this->itemCount >= arg.itemCount };
auto currThisPtr{ this->headPtr };
auto currArgPtr{ arg.headPtr };
if (!this->isEmpty())
{
currThisPtr->setItem(currArgPtr->getItem());
for (int i = 2; i <= ((isThisLarger) ? arg.itemCount : this->itemCount); i++) {
currThisPtr = currThisPtr->getNext();
currArgPtr = currArgPtr->getNext();
currThisPtr->setItem(currArgPtr->getItem());
}
// If the calling list is larger then tidy up the end.
if (isThisLarger) {
this->itemCount = arg.itemCount;
currThisPtr->setNext(nullptr);
}
}
// Create new nodes and/or finish copying the entries.
if (!isThisLarger) {
currArgPtr = currArgPtr->getNext();
auto newNodePtr{ std::make_shared>(currArgPtr->getItem()) };
auto prevNodePtr{ currThisPtr };
prevNodePtr->setNext(newNodePtr);
if (this->isEmpty())
this->headPtr = newNodePtr;
for (int i = this->itemCount+1; i <= arg.itemCount; i++) {
newNodePtr = std::make_shared>(currArgPtr->getItem());
prevNodePtr->setNext(newNodePtr);
prevNodePtr = newNodePtr;
currArgPtr = currArgPtr->getNext();
}
this->itemCount = arg.itemCount;
}
}
#endif
Solution
#ifndef LINKED_LIST_
#define LINKED_LIST_
template
class LinkedList {
private:
std::shared_ptr> headPtr; // Pointer to first node in the chain;
// (contains the first entry in the list)
int itemCount; // Current count of list items
std::shared_ptr> getNodeAt(int position) const;
public:
LinkedList();
LinkedList(const LinkedList& aList);
virtual ~LinkedList();
bool isEmpty() const;
int getLength() const;
bool insert(int newPosition, const ItemType& newEntry);
bool remove(int position);
void clear();
/** throw PrecondViolatedExcept if position < 1 or
position > getLength(). */
ItemType getEntry(int position) const throw(PrecondViolatedExcept);
/** throw PrecondViolatedExcept if position < 1 or
position > getLength(). */
void replace(int position, const ItemType& newEntry)
throw(PrecondViolatedExcept);
// Operator Overloading
void operator = (const LinkedList& arg);
friend std::ostream& operator << (std::ostream& os, const LinkedList& arg)
{
os << "There are " << arg.getLength() << " values in the list:" << std::endl;
for (int i{ 1 }; i <= arg.getLength(); i++) {
os << arg.getEntry(i) << std::endl;
}
os << std::endl << std::endl << std::endl << std::endl;
return os;
}
};
// Returns a pointer to the Node at the given position.
template
std::shared_ptr> LinkedList::getNodeAt (int position) const {
std::shared_ptr> currPtr{ headPtr };
for (int i{ 1 }; i < position; i++)
currPtr = currPtr->getNext();
return currPtr;
}
// Default constructor.
template
LinkedList::LinkedList() {
headPtr = nullptr;
itemCount = 0;
}
// Copy constructor.
template
LinkedList::LinkedList(const LinkedList& aList) {
itemCount = aList.getLength();
auto currPtr{ aList.headPtr };
auto newNodePtr{ headPtr = std::make_shared>(currPtr->getItem()) };
auto prevNodePtr{ newNodePtr };
currPtr = currPtr->getNext();
for (int i{ 2 }; i <= itemCount; i++) {
newNodePtr = std::make_shared>(currPtr->getItem());
prevNodePtr->setNext(newNodePtr);
prevNodePtr = newNodePtr;
currPtr = currPtr->getNext();
}
}
// Destructor.
template
LinkedList::~LinkedList() {
headPtr = nullptr;
itemCount = 0;
}
// Accessor/Info Functions.
template
bool LinkedList::isEmpty() const {
return (itemCount > 0)?0:1;
}
template
int LinkedList::getLength() const {
return itemCount;
}
// Places a Node at a given position (element at the same position is now pos+1).
template
bool LinkedList::insert(const int newPosition,
const ItemType& newEntry)
{
bool ableToInsert{ (newPosition >= 1) &&
(newPosition <= itemCount + 1) };
if (ableToInsert)
{
// Create a new node containing the new entry
auto newNodePtr{ std::make_shared>(newEntry) };
// Attach new node to chain
if (newPosition == 1)
{
// Insert new node at beginning of chain
newNodePtr->setNext(headPtr);
headPtr = newNodePtr;
}
else
{
// Find node that will be before new node
auto prevPtr{ getNodeAt(newPosition - 1) };
// Insert new node after node to which prevPtr points
newNodePtr->setNext(prevPtr->getNext());
prevPtr->setNext(newNodePtr);
} // end if
itemCount++; // Increase count of entries
} // end if
return ableToInsert;
} // end insert
// Removes the Node at the given position.
template
bool LinkedList::remove(const int position)
{
bool ableToRemove = (position >= 1) && (position <= itemCount);
if (ableToRemove)
{
if (position == 1)
{
// Remove the first node in the chain
headPtr = headPtr->getNext();
}
else
{
// Find node that is before the one to delete
auto prevPtr{ getNodeAt(position - 1) };
// Point to node to delete
auto curPtr{ prevPtr->getNext() };
// Disconnect indicated node from chain by connecting the
// prior node with the one after
prevPtr->setNext(curPtr->getNext());
} // end if
itemCount--; // Decrease count of entries
} // end if
return ableToRemove;
} // end remove
// Replaces the Entry in the given Node with the new Entry.
template
void LinkedList::replace(const int position, const ItemType& newEntry)
throw(PrecondViolatedExcept)
{
if (position > this->getLength() || position < 1)
throw PrecondViolatedExcept("replace() called with a position out of bounds.");
else
getNodeAt(position)->setItem(newEntry);
}
template
void LinkedList::clear()
{
headPtr = nullptr;
itemCount = 0;
} // end clear
template
ItemType LinkedList::getEntry(int position) const throw(PrecondViolatedExcept)
{
if (position > this->getLength() || position < 1)
throw PrecondViolatedExcept("getEntry() called with a position out of bounds.");
else
return getNodeAt(position)->getItem();
}
// Makes the calling Linked List's entries the same as the given Linked List.
template
void LinkedList::operator = (const LinkedList& arg) {
if (arg.isEmpty())
return;
// First section copies the given list into the calling list's existing nodes.
bool isThisLarger{ this->itemCount >= arg.itemCount };
auto currThisPtr{ this->headPtr };
auto currArgPtr{ arg.headPtr };
if (!this->isEmpty())
{
currThisPtr->setItem(currArgPtr->getItem());
for (int i = 2; i <= ((isThisLarger) ? arg.itemCount : this->itemCount); i++) {
currThisPtr = currThisPtr->getNext();
currArgPtr = currArgPtr->getNext();
currThisPtr->setItem(currArgPtr->getItem());
}
// If the calling list is larger then tidy up the end.
if (isThisLarger) {
this->itemCount = arg.itemCount;
currThisPtr->setNext(nullptr);
}
}
// Create new nodes and/or finish copying the entries.
if (!isThisLarger) {
currArgPtr = currArgPtr->getNext();
auto newNodePtr{ std::make_shared>(currArgPtr->getItem()) };
auto prevNodePtr{ currThisPtr };
prevNodePtr->setNext(newNodePtr);
if (this->isEmpty())
this->headPtr = newNodePtr;
for (int i = this->itemCount+1; i <= arg.itemCount; i++) {
newNodePtr = std::make_shared>(currArgPtr->getItem());
prevNodePtr->setNext(newNodePtr);
prevNodePtr = newNodePtr;
currArgPtr = currArgPtr->getNext();
}
this->itemCount = arg.itemCount;
}
}
#endif

More Related Content

Similar to #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf (20)

DOCX
Write a program to find the number of comparisons using the binary se.docx
ajoy21
 
PDF
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
rambagra74
 
PDF
Can you please debug this Thank you in advance! This program is sup.pdf
FashionBoutiquedelhi
 
DOCX
Linked lists
George Scott IV
 
PDF
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
PDF
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
mail931892
 
PPT
dynamicList.ppt
ssuser0be977
 
PDF
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
PPT
강의자료8
Young Wook Kim
 
PDF
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
climatecontrolsv
 
PDF
How do you stop infinite loop Because I believe that it is making a.pdf
feelinggift
 
PDF
In C++ I need help with this method that Im trying to write fillLi.pdf
fantoosh1
 
PPTX
Link List Programming Linked List in Cpp
Anil Yadav
 
PDF
I want help in the following C++ programming task. Please do coding .pdf
bermanbeancolungak45
 
PDF
Please teach me how to fix the errors and where should be modified. .pdf
amarndsons
 
RTF
Sorter
Thomas Knudstrup
 
PDF
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
PDF
In C++Write a recursive function to determine whether or not a Lin.pdf
flashfashioncasualwe
 
PDF
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
mail931892
 
PDF
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 
Write a program to find the number of comparisons using the binary se.docx
ajoy21
 
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
rambagra74
 
Can you please debug this Thank you in advance! This program is sup.pdf
FashionBoutiquedelhi
 
Linked lists
George Scott IV
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
mail931892
 
dynamicList.ppt
ssuser0be977
 
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
강의자료8
Young Wook Kim
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
climatecontrolsv
 
How do you stop infinite loop Because I believe that it is making a.pdf
feelinggift
 
In C++ I need help with this method that Im trying to write fillLi.pdf
fantoosh1
 
Link List Programming Linked List in Cpp
Anil Yadav
 
I want help in the following C++ programming task. Please do coding .pdf
bermanbeancolungak45
 
Please teach me how to fix the errors and where should be modified. .pdf
amarndsons
 
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
In C++Write a recursive function to determine whether or not a Lin.pdf
flashfashioncasualwe
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
mail931892
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 

More from angelsfashion1 (20)

PDF
The density of water. The shape of protein molecu.pdf
angelsfashion1
 
PDF
SrCl2 So.pdf
angelsfashion1
 
PDF
Silica gel is a very polar absorbent, and so ho.pdf
angelsfashion1
 
PDF
PbI2-Pb2+ and 2I- Molar Concentration of Iodide.pdf
angelsfashion1
 
PDF
NiSO4 as its a weak salt and will not dissociates.pdf
angelsfashion1
 
PDF
NaCl is ionic compound and polar where as benzene.pdf
angelsfashion1
 
PDF
No. Sodium lauryl sulfate will not form insoluble.pdf
angelsfashion1
 
PDF
Moles of H2O = 4.564=6.75 moles .pdf
angelsfashion1
 
PDF
it is ribose and the other is deoxyribose .pdf
angelsfashion1
 
PDF
True.It is a confirmal mapping transforming imaginary axis of s-pl.pdf
angelsfashion1
 
PDF
These are two of the three major perspectives on sociology. Each of .pdf
angelsfashion1
 
PDF
I have no Idea sorry. .pdf
angelsfashion1
 
PDF
The main body of the new policy The employees can write blogs to .pdf
angelsfashion1
 
PDF
The emotional and psychological effects the HIVAIDS epidemic on the.pdf
angelsfashion1
 
PDF
Specific heat of water = 4.184 Jg.oCHeat released by dissolution .pdf
angelsfashion1
 
PDF
Solution is simple.Comments added start with calling a funct.pdf
angelsfashion1
 
PDF
Since the gene responsible for the color of pea and shape of seed of.pdf
angelsfashion1
 
PDF
HClO4(aq) appear as H+ (aq) and ClO4 - (aq)Na2SO4.pdf
angelsfashion1
 
PDF
Questionaccording to this rule of solubility rules most sulfat.pdf
angelsfashion1
 
PDF
Option (d) is correct. This is because dominant mutation involves si.pdf
angelsfashion1
 
The density of water. The shape of protein molecu.pdf
angelsfashion1
 
SrCl2 So.pdf
angelsfashion1
 
Silica gel is a very polar absorbent, and so ho.pdf
angelsfashion1
 
PbI2-Pb2+ and 2I- Molar Concentration of Iodide.pdf
angelsfashion1
 
NiSO4 as its a weak salt and will not dissociates.pdf
angelsfashion1
 
NaCl is ionic compound and polar where as benzene.pdf
angelsfashion1
 
No. Sodium lauryl sulfate will not form insoluble.pdf
angelsfashion1
 
Moles of H2O = 4.564=6.75 moles .pdf
angelsfashion1
 
it is ribose and the other is deoxyribose .pdf
angelsfashion1
 
True.It is a confirmal mapping transforming imaginary axis of s-pl.pdf
angelsfashion1
 
These are two of the three major perspectives on sociology. Each of .pdf
angelsfashion1
 
I have no Idea sorry. .pdf
angelsfashion1
 
The main body of the new policy The employees can write blogs to .pdf
angelsfashion1
 
The emotional and psychological effects the HIVAIDS epidemic on the.pdf
angelsfashion1
 
Specific heat of water = 4.184 Jg.oCHeat released by dissolution .pdf
angelsfashion1
 
Solution is simple.Comments added start with calling a funct.pdf
angelsfashion1
 
Since the gene responsible for the color of pea and shape of seed of.pdf
angelsfashion1
 
HClO4(aq) appear as H+ (aq) and ClO4 - (aq)Na2SO4.pdf
angelsfashion1
 
Questionaccording to this rule of solubility rules most sulfat.pdf
angelsfashion1
 
Option (d) is correct. This is because dominant mutation involves si.pdf
angelsfashion1
 
Ad

Recently uploaded (20)

PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Define Translation to Custom Module And Add a new language in Odoo 18
Celine George
 
PPTX
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
PDF
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PPTX
How to Manage Promotions in Odoo 18 Sales
Celine George
 
PPTX
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
PPTX
CONVULSIVE DISORDERS: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
Accounting Skills Paper-I, Preparation of Vouchers
Dr. Sushil Bansode
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Define Translation to Custom Module And Add a new language in Odoo 18
Celine George
 
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
How to Manage Promotions in Odoo 18 Sales
Celine George
 
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
CONVULSIVE DISORDERS: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Accounting Skills Paper-I, Preparation of Vouchers
Dr. Sushil Bansode
 
Ad

#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf

  • 1. #ifndef LINKED_LIST_ #define LINKED_LIST_ template class LinkedList { private: std::shared_ptr> headPtr; // Pointer to first node in the chain; // (contains the first entry in the list) int itemCount; // Current count of list items std::shared_ptr> getNodeAt(int position) const; public: LinkedList(); LinkedList(const LinkedList& aList); virtual ~LinkedList(); bool isEmpty() const; int getLength() const; bool insert(int newPosition, const ItemType& newEntry); bool remove(int position); void clear(); /** throw PrecondViolatedExcept if position < 1 or position > getLength(). */ ItemType getEntry(int position) const throw(PrecondViolatedExcept); /** throw PrecondViolatedExcept if position < 1 or position > getLength(). */ void replace(int position, const ItemType& newEntry) throw(PrecondViolatedExcept); // Operator Overloading void operator = (const LinkedList& arg); friend std::ostream& operator << (std::ostream& os, const LinkedList& arg) { os << "There are " << arg.getLength() << " values in the list:" << std::endl; for (int i{ 1 }; i <= arg.getLength(); i++) {
  • 2. os << arg.getEntry(i) << std::endl; } os << std::endl << std::endl << std::endl << std::endl; return os; } }; // Returns a pointer to the Node at the given position. template std::shared_ptr> LinkedList::getNodeAt (int position) const { std::shared_ptr> currPtr{ headPtr }; for (int i{ 1 }; i < position; i++) currPtr = currPtr->getNext(); return currPtr; } // Default constructor. template LinkedList::LinkedList() { headPtr = nullptr; itemCount = 0; } // Copy constructor. template LinkedList::LinkedList(const LinkedList& aList) { itemCount = aList.getLength(); auto currPtr{ aList.headPtr }; auto newNodePtr{ headPtr = std::make_shared>(currPtr->getItem()) }; auto prevNodePtr{ newNodePtr }; currPtr = currPtr->getNext(); for (int i{ 2 }; i <= itemCount; i++) { newNodePtr = std::make_shared>(currPtr->getItem()); prevNodePtr->setNext(newNodePtr); prevNodePtr = newNodePtr; currPtr = currPtr->getNext(); } } // Destructor.
  • 3. template LinkedList::~LinkedList() { headPtr = nullptr; itemCount = 0; } // Accessor/Info Functions. template bool LinkedList::isEmpty() const { return (itemCount > 0)?0:1; } template int LinkedList::getLength() const { return itemCount; } // Places a Node at a given position (element at the same position is now pos+1). template bool LinkedList::insert(const int newPosition, const ItemType& newEntry) { bool ableToInsert{ (newPosition >= 1) && (newPosition <= itemCount + 1) }; if (ableToInsert) { // Create a new node containing the new entry auto newNodePtr{ std::make_shared>(newEntry) }; // Attach new node to chain if (newPosition == 1) { // Insert new node at beginning of chain newNodePtr->setNext(headPtr); headPtr = newNodePtr; } else { // Find node that will be before new node
  • 4. auto prevPtr{ getNodeAt(newPosition - 1) }; // Insert new node after node to which prevPtr points newNodePtr->setNext(prevPtr->getNext()); prevPtr->setNext(newNodePtr); } // end if itemCount++; // Increase count of entries } // end if return ableToInsert; } // end insert // Removes the Node at the given position. template bool LinkedList::remove(const int position) { bool ableToRemove = (position >= 1) && (position <= itemCount); if (ableToRemove) { if (position == 1) { // Remove the first node in the chain headPtr = headPtr->getNext(); } else { // Find node that is before the one to delete auto prevPtr{ getNodeAt(position - 1) }; // Point to node to delete auto curPtr{ prevPtr->getNext() }; // Disconnect indicated node from chain by connecting the // prior node with the one after prevPtr->setNext(curPtr->getNext()); } // end if
  • 5. itemCount--; // Decrease count of entries } // end if return ableToRemove; } // end remove // Replaces the Entry in the given Node with the new Entry. template void LinkedList::replace(const int position, const ItemType& newEntry) throw(PrecondViolatedExcept) { if (position > this->getLength() || position < 1) throw PrecondViolatedExcept("replace() called with a position out of bounds."); else getNodeAt(position)->setItem(newEntry); } template void LinkedList::clear() { headPtr = nullptr; itemCount = 0; } // end clear template ItemType LinkedList::getEntry(int position) const throw(PrecondViolatedExcept) { if (position > this->getLength() || position < 1) throw PrecondViolatedExcept("getEntry() called with a position out of bounds."); else return getNodeAt(position)->getItem(); } // Makes the calling Linked List's entries the same as the given Linked List. template void LinkedList::operator = (const LinkedList& arg) { if (arg.isEmpty()) return; // First section copies the given list into the calling list's existing nodes.
  • 6. bool isThisLarger{ this->itemCount >= arg.itemCount }; auto currThisPtr{ this->headPtr }; auto currArgPtr{ arg.headPtr }; if (!this->isEmpty()) { currThisPtr->setItem(currArgPtr->getItem()); for (int i = 2; i <= ((isThisLarger) ? arg.itemCount : this->itemCount); i++) { currThisPtr = currThisPtr->getNext(); currArgPtr = currArgPtr->getNext(); currThisPtr->setItem(currArgPtr->getItem()); } // If the calling list is larger then tidy up the end. if (isThisLarger) { this->itemCount = arg.itemCount; currThisPtr->setNext(nullptr); } } // Create new nodes and/or finish copying the entries. if (!isThisLarger) { currArgPtr = currArgPtr->getNext(); auto newNodePtr{ std::make_shared>(currArgPtr->getItem()) }; auto prevNodePtr{ currThisPtr }; prevNodePtr->setNext(newNodePtr); if (this->isEmpty()) this->headPtr = newNodePtr; for (int i = this->itemCount+1; i <= arg.itemCount; i++) { newNodePtr = std::make_shared>(currArgPtr->getItem()); prevNodePtr->setNext(newNodePtr); prevNodePtr = newNodePtr; currArgPtr = currArgPtr->getNext(); } this->itemCount = arg.itemCount;
  • 7. } } #endif Solution #ifndef LINKED_LIST_ #define LINKED_LIST_ template class LinkedList { private: std::shared_ptr> headPtr; // Pointer to first node in the chain; // (contains the first entry in the list) int itemCount; // Current count of list items std::shared_ptr> getNodeAt(int position) const; public: LinkedList(); LinkedList(const LinkedList& aList); virtual ~LinkedList(); bool isEmpty() const; int getLength() const; bool insert(int newPosition, const ItemType& newEntry); bool remove(int position); void clear(); /** throw PrecondViolatedExcept if position < 1 or position > getLength(). */ ItemType getEntry(int position) const throw(PrecondViolatedExcept); /** throw PrecondViolatedExcept if position < 1 or position > getLength(). */ void replace(int position, const ItemType& newEntry) throw(PrecondViolatedExcept); // Operator Overloading
  • 8. void operator = (const LinkedList& arg); friend std::ostream& operator << (std::ostream& os, const LinkedList& arg) { os << "There are " << arg.getLength() << " values in the list:" << std::endl; for (int i{ 1 }; i <= arg.getLength(); i++) { os << arg.getEntry(i) << std::endl; } os << std::endl << std::endl << std::endl << std::endl; return os; } }; // Returns a pointer to the Node at the given position. template std::shared_ptr> LinkedList::getNodeAt (int position) const { std::shared_ptr> currPtr{ headPtr }; for (int i{ 1 }; i < position; i++) currPtr = currPtr->getNext(); return currPtr; } // Default constructor. template LinkedList::LinkedList() { headPtr = nullptr; itemCount = 0; } // Copy constructor. template LinkedList::LinkedList(const LinkedList& aList) { itemCount = aList.getLength(); auto currPtr{ aList.headPtr }; auto newNodePtr{ headPtr = std::make_shared>(currPtr->getItem()) }; auto prevNodePtr{ newNodePtr }; currPtr = currPtr->getNext(); for (int i{ 2 }; i <= itemCount; i++) { newNodePtr = std::make_shared>(currPtr->getItem()); prevNodePtr->setNext(newNodePtr);
  • 9. prevNodePtr = newNodePtr; currPtr = currPtr->getNext(); } } // Destructor. template LinkedList::~LinkedList() { headPtr = nullptr; itemCount = 0; } // Accessor/Info Functions. template bool LinkedList::isEmpty() const { return (itemCount > 0)?0:1; } template int LinkedList::getLength() const { return itemCount; } // Places a Node at a given position (element at the same position is now pos+1). template bool LinkedList::insert(const int newPosition, const ItemType& newEntry) { bool ableToInsert{ (newPosition >= 1) && (newPosition <= itemCount + 1) }; if (ableToInsert) { // Create a new node containing the new entry auto newNodePtr{ std::make_shared>(newEntry) }; // Attach new node to chain if (newPosition == 1) { // Insert new node at beginning of chain newNodePtr->setNext(headPtr);
  • 10. headPtr = newNodePtr; } else { // Find node that will be before new node auto prevPtr{ getNodeAt(newPosition - 1) }; // Insert new node after node to which prevPtr points newNodePtr->setNext(prevPtr->getNext()); prevPtr->setNext(newNodePtr); } // end if itemCount++; // Increase count of entries } // end if return ableToInsert; } // end insert // Removes the Node at the given position. template bool LinkedList::remove(const int position) { bool ableToRemove = (position >= 1) && (position <= itemCount); if (ableToRemove) { if (position == 1) { // Remove the first node in the chain headPtr = headPtr->getNext(); } else { // Find node that is before the one to delete auto prevPtr{ getNodeAt(position - 1) }; // Point to node to delete auto curPtr{ prevPtr->getNext() };
  • 11. // Disconnect indicated node from chain by connecting the // prior node with the one after prevPtr->setNext(curPtr->getNext()); } // end if itemCount--; // Decrease count of entries } // end if return ableToRemove; } // end remove // Replaces the Entry in the given Node with the new Entry. template void LinkedList::replace(const int position, const ItemType& newEntry) throw(PrecondViolatedExcept) { if (position > this->getLength() || position < 1) throw PrecondViolatedExcept("replace() called with a position out of bounds."); else getNodeAt(position)->setItem(newEntry); } template void LinkedList::clear() { headPtr = nullptr; itemCount = 0; } // end clear template ItemType LinkedList::getEntry(int position) const throw(PrecondViolatedExcept) { if (position > this->getLength() || position < 1) throw PrecondViolatedExcept("getEntry() called with a position out of bounds."); else return getNodeAt(position)->getItem(); } // Makes the calling Linked List's entries the same as the given Linked List.
  • 12. template void LinkedList::operator = (const LinkedList& arg) { if (arg.isEmpty()) return; // First section copies the given list into the calling list's existing nodes. bool isThisLarger{ this->itemCount >= arg.itemCount }; auto currThisPtr{ this->headPtr }; auto currArgPtr{ arg.headPtr }; if (!this->isEmpty()) { currThisPtr->setItem(currArgPtr->getItem()); for (int i = 2; i <= ((isThisLarger) ? arg.itemCount : this->itemCount); i++) { currThisPtr = currThisPtr->getNext(); currArgPtr = currArgPtr->getNext(); currThisPtr->setItem(currArgPtr->getItem()); } // If the calling list is larger then tidy up the end. if (isThisLarger) { this->itemCount = arg.itemCount; currThisPtr->setNext(nullptr); } } // Create new nodes and/or finish copying the entries. if (!isThisLarger) { currArgPtr = currArgPtr->getNext(); auto newNodePtr{ std::make_shared>(currArgPtr->getItem()) }; auto prevNodePtr{ currThisPtr }; prevNodePtr->setNext(newNodePtr); if (this->isEmpty()) this->headPtr = newNodePtr; for (int i = this->itemCount+1; i <= arg.itemCount; i++) { newNodePtr = std::make_shared>(currArgPtr->getItem());
  • 13. prevNodePtr->setNext(newNodePtr); prevNodePtr = newNodePtr; currArgPtr = currArgPtr->getNext(); } this->itemCount = arg.itemCount; } } #endif