SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
#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

Weitere ähnliche Inhalte

Ähnlich wie #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.pdframbagra74
 
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.pdfFashionBoutiquedelhi
 
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-.pdfvishalateen
 
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.pdfmail931892
 
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.pdfmalavshah9013
 
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.pdfclimatecontrolsv
 
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.pdffeelinggift
 
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.pdffantoosh1
 
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 .pdfbermanbeancolungak45
 
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. .pdfamarndsons
 
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.pdfamazing2001
 
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.pdfflashfashioncasualwe
 
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.pdfmail931892
 
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.pdffmac5
 
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
 

Ähnlich wie #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
 

Mehr von 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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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 .pdfangelsfashion1
 
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 .pdfangelsfashion1
 
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.pdfangelsfashion1
 
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 .pdfangelsfashion1
 
I have no Idea sorry. .pdf
                     I have no Idea sorry.                            .pdf                     I have no Idea sorry.                            .pdf
I have no Idea sorry. .pdfangelsfashion1
 
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 .pdfangelsfashion1
 
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.pdfangelsfashion1
 
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 .pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 
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.pdfangelsfashion1
 

Mehr von 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
 

Kürzlich hochgeladen

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 

Kürzlich hochgeladen (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 

#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