#1 Added remove method to Linked List
This commit is contained in:
		@@ -57,7 +57,9 @@ namespace Datastructures {
 | 
			
		||||
		if (index == 0 || this->mCount == 0)
 | 
			
		||||
		{//If the new item needs to go into the head of the linked list.
 | 
			
		||||
			mHead = std::make_shared<Nodes::LinkedListNode<T>>(value, mHead);
 | 
			
		||||
		} else {
 | 
			
		||||
		} 
 | 
			
		||||
		else 
 | 
			
		||||
		{
 | 
			
		||||
			//Get the node before the one we are going to be inserting
 | 
			
		||||
			std::shared_ptr<Nodes::LinkedListNode<T>> node = this->getIndex(index-1);
 | 
			
		||||
			//If node is nullptr, index is out of range
 | 
			
		||||
@@ -66,12 +68,34 @@ namespace Datastructures {
 | 
			
		||||
 | 
			
		||||
			node->next = std::make_shared<Nodes::LinkedListNode<T>>(value, node->next);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		//Append the new value into a new node.
 | 
			
		||||
		mCount++;
 | 
			
		||||
		return true;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	template <typename T> 
 | 
			
		||||
	bool LinkedList<T>::remove(int index) {
 | 
			
		||||
		//If the list is empty
 | 
			
		||||
		if (this->mCount == 0)
 | 
			
		||||
			return false;
 | 
			
		||||
 | 
			
		||||
		//Check if we are looking to remove the head node (0)
 | 
			
		||||
		if (index == 0)
 | 
			
		||||
		{
 | 
			
		||||
			this->mHead = this->mHead->next;
 | 
			
		||||
		}
 | 
			
		||||
		else
 | 
			
		||||
		{
 | 
			
		||||
			//Get the node before the one that is about to be removed
 | 
			
		||||
			std::shared_ptr<Nodes::LinkedListNode<T>> node = this->getIndex(index - 1);
 | 
			
		||||
			//Point this node to the node pointed to by the one about to be removed
 | 
			
		||||
			node->next = node->next->next;
 | 
			
		||||
		}
 | 
			
		||||
		//Reduce the total count of nodes
 | 
			
		||||
		mCount--;
 | 
			
		||||
		return true;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	template <typename T>
 | 
			
		||||
	std::shared_ptr<Nodes::LinkedListNode<T>> LinkedList<T>::getIndex(int index) {
 | 
			
		||||
		//Check if the value lies within the range of the list.
 | 
			
		||||
 
 | 
			
		||||
@@ -5,4 +5,5 @@ int main() {
 | 
			
		||||
	list.append(5);
 | 
			
		||||
	list.append(200);
 | 
			
		||||
	list.insert(20, 2);
 | 
			
		||||
	list.remove(0);
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user