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

5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
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
Can you please debug this Thank you in advance! This program is sup.pdfCan you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdf
FashionBoutiquedelhi
 
Linked lists
Linked listsLinked lists
Linked lists
George Scott IV
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
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
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
mail931892
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
ssuser0be977
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
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
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
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
In C++ I need help with this method that Im trying to write fillLi.pdfIn C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdf
fantoosh1
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
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
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdf
amarndsons
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
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
How do I fix it in LinkedList.javaLinkedList.java Define.pdfHow do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
mail931892
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 
Data structures cs301 power point slides lecture 03
Data structures   cs301 power point slides lecture 03Data structures   cs301 power point slides lecture 03
Data structures cs301 power point slides lecture 03Nasir Mehmood
 

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

5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
 
Can you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdfCan you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdf
 
Linked lists
Linked listsLinked lists
Linked lists
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
강의자료8
강의자료8강의자료8
강의자료8
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
 
In C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdfIn C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdf
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdf
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdf
 
Sorter
SorterSorter
Sorter
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfHow do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdf
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Data structures cs301 power point slides lecture 03
Data structures   cs301 power point slides lecture 03Data structures   cs301 power point slides lecture 03
Data structures cs301 power point slides lecture 03
 

More from angelsfashion1

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

More from angelsfashion1 (20)

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

Recently uploaded

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 

Recently uploaded (20)

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 

#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