Question

In: Computer Science

Working with Linked Lists in C++ Tasks As stated in the objectives, you have two methods...

Working with Linked Lists in C++

Tasks

As stated in the objectives, you have two methods to implement. These methods (which contain TODO comments) are found in linked_list.cpp.

Part 1

Implement the copy constructor; use the LinkedBag as inspiration for your solution as the technique of creating a deep copy is essentially the same.

Part 2

Implement the replace method.

//linked_list.cpp

#include "linked_list.h"  // Header file
#include <cassert>

template<class Object>
LinkedList<Object>::LinkedList()
        : headPtr( nullptr ), itemCount( 0 )
{
}  // end default constructor

template<class Object>
LinkedList<Object>::LinkedList(const LinkedList<Object>& aList)
        : itemCount( aList.itemCount )
{
    // TODO: Implement me
}  // end copy constructor

template<class Object>
LinkedList<Object>::~LinkedList()
{
    clear();
}  // end destructor

template<class Object>
bool LinkedList<Object>::isEmpty() const
{
    return itemCount == 0;
}  // end isEmpty

template<class Object>
int LinkedList<Object>::getLength() const
{
    return itemCount;
}  // end getLength

template<class Object>
bool LinkedList<Object>::insert(int newPosition, const Object& newEntry)
{
    bool ableToInsert = (newPosition >= 1) && (newPosition <= itemCount + 1);
    if (ableToInsert)
    {
        // Create a new node containing the new entry
        auto newNodePtr = new Node<Object>( 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
            Node<Object>* 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

template<class Object>
bool LinkedList<Object>::remove(int position)
{
    bool ableToRemove = (position >= 1) && (position <= itemCount);
    if (ableToRemove)
    {
        Node<Object>* curPtr = nullptr;
        if (position == 1)
        {
            // Remove the first node in the chain
            curPtr = headPtr; // Save pointer to node
            headPtr = headPtr->getNext();
        }
        else
        {
            // Find node that is before the one to delete
            Node<Object>* prevPtr = getNodeAt( position - 1 );

            // Point to node to delete
            curPtr = prevPtr->getNext();

            // Disconnect indicated node from chain by connecting the
            // prior node with the one after
            prevPtr->setNext( curPtr->getNext());
        }  // end if

        // Return node to system
        curPtr->setNext( nullptr );
        delete curPtr;
        curPtr = nullptr;

        itemCount--;  // Decrease count of entries
    }  // end if

    return ableToRemove;
}  // end remove

template<class Object>
void LinkedList<Object>::clear()
{
    while (!isEmpty())
        remove( 1 );
}  // end clear

template<class Object>
Object LinkedList<Object>::getEntry(int position) const noexcept( false )
{
    // Enforce precondition
    bool ableToGet = (position >= 1) && (position <= itemCount);
    if (ableToGet)
    {
        Node<Object>* nodePtr = getNodeAt( position );
        return nodePtr->getItem();
    }
    else
    {
        std::string message = "getEntry() called with an empty list or ";
        message = message + "invalid position.";
        throw (PrecondViolatedExcep( message ));
    }  // end if
}  // end getEntry

template<class Object>
void LinkedList<Object>::replace(int position, const Object& newEntry) noexcept( false )
{
    // TODO: Implement me; throw a PrecondViolatedExcep if preconditions aren't met
}  // end replace

template<class Object>
Node<Object>* LinkedList<Object>::getNodeAt(int position) const noexcept( false )
{
    // Check preconditions
    if ((position < 1) || (position > itemCount))
    {
        std::string message = "private helper method called with an invalid position";
        throw (PrecondViolatedExcep( message ));
    }

    // Count from the beginning of the chain
    Node<Object>* curPtr = headPtr;
    for (int skip = 1; skip < position; skip++)
    {
        curPtr = curPtr->getNext();
    }

    return curPtr;
}  // end getNodeAt
//  End of implementation file.

Solutions

Expert Solution

#include "linked_list.h" // Header file
#include <cassert>

template<class Object>
LinkedList<Object>::LinkedList()
: headPtr( nullptr ), itemCount( 0 )
{
} // end default constructor

template<class Object>
LinkedList<Object>::LinkedList(const LinkedList<Object>& aList)
: itemCount( aList.itemCount )
{
   // initialize headPtr to null
headPtr = nullptr;
  
   // set listCurPtr to head node of aList
   Node<Object>* listCurPtr = aList.headPtr;
  
   // set curPtr to head node of this list
   Node<Object>* curPtr = headPtr;
  
   // loop over the aList
   while(listCurPtr != nullptr)
   {
       // create a new node with item from listCurPtr
       Node<Object>* node = new Node<Object>(listCurPtr->getItem());
      
       // headPtr is null, set node to headPtr
       if(headPtr == nullptr)
       {
           headPtr = node;
           curPtr = headPtr; // set curr to headPtr
       }
       else // headPtr is not null
       {
           curPtr->setNext(node); // set next of curPtr to node
           curPtr = curPtr->getNext(); // move curPtr to the newly inserted node
       }
      
       // move listCurPtr to next node
       listCurPtr = listCurPtr->getNext();
   }
  
} // end copy constructor

template<class Object>
LinkedList<Object>::~LinkedList()
{
clear();
} // end destructor

template<class Object>
bool LinkedList<Object>::isEmpty() const
{
return itemCount == 0;
} // end isEmpty

template<class Object>
int LinkedList<Object>::getLength() const
{
return itemCount;
} // end getLength

template<class Object>
bool LinkedList<Object>::insert(int newPosition, const Object& newEntry)
{
bool ableToInsert = (newPosition >= 1) && (newPosition <= itemCount + 1);
if (ableToInsert)
{
// Create a new node containing the new entry
auto newNodePtr = new Node<Object>( 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
Node<Object>* 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

template<class Object>
bool LinkedList<Object>::remove(int position)
{
bool ableToRemove = (position >= 1) && (position <= itemCount);
if (ableToRemove)
{
Node<Object>* curPtr = nullptr;
if (position == 1)
{
// Remove the first node in the chain
curPtr = headPtr; // Save pointer to node
headPtr = headPtr->getNext();
}
else
{
// Find node that is before the one to delete
Node<Object>* prevPtr = getNodeAt( position - 1 );

// Point to node to delete
curPtr = prevPtr->getNext();

// Disconnect indicated node from chain by connecting the
// prior node with the one after
prevPtr->setNext( curPtr->getNext());
} // end if

// Return node to system
curPtr->setNext( nullptr );
delete curPtr;
curPtr = nullptr;

itemCount--; // Decrease count of entries
} // end if

return ableToRemove;
} // end remove

template<class Object>
void LinkedList<Object>::clear()
{
while (!isEmpty())
remove( 1 );
} // end clear

template<class Object>
Object LinkedList<Object>::getEntry(int position) const noexcept( false )
{
// Enforce precondition
bool ableToGet = (position >= 1) && (position <= itemCount);
if (ableToGet)
{
Node<Object>* nodePtr = getNodeAt( position );
return nodePtr->getItem();
}
else
{
std::string message = "getEntry() called with an empty list or ";
message = message + "invalid position.";
throw (PrecondViolatedExcep( message ));
} // end if
} // end getEntry

template<class Object>
void LinkedList<Object>::replace(int position, const Object& newEntry) noexcept( false )
{
   // invalid position, throw PrecondViolatedExcep
if(position < 1 || position > itemCount)
   {
       std::string message = "replace() called with an invalid position";
       throw (PrecondViolatedExcep( message ));
   }

   // get the node at position
   Node<Object>* nodePtr = getNodeAt(position);
  
   // update the item of nodePtr to newEntry
   nodePtr->setItem(newEntry); // assuming Node class contains a method setItem to update the item of the node  
      
} // end replace

template<class Object>
Node<Object>* LinkedList<Object>::getNodeAt(int position) const noexcept( false )
{
// Check preconditions
if ((position < 1) || (position > itemCount))
{
std::string message = "private helper method called with an invalid position";
throw (PrecondViolatedExcep( message ));
}

// Count from the beginning of the chain
Node<Object>* curPtr = headPtr;
for (int skip = 1; skip < position; skip++)
{
curPtr = curPtr->getNext();
}

return curPtr;
} // end getNodeAt
// End of implementation file.


Related Solutions

C++ Linked Lists Practice your understanding of linked lists in C++ by creating a list of...
C++ Linked Lists Practice your understanding of linked lists in C++ by creating a list of songs/artist pairs. Allow your user to add song / artist pairs to the list, remove songs (and associated artist) from the list and be sure to also write a function to print the list! Have fun! Make sure you show your implementation of the use of vectors in this lab (You can use them too ) You MUST modularize your code ( meaning, there...
Using C++, you will create a program, where you will create two doubly linked lists. These...
Using C++, you will create a program, where you will create two doubly linked lists. These doubly linked lists will contain integers within them. Using the numbers in both of these linked lists, you add the numbers together, and insert the addition of the two numbers into a singly linked list. the input can be from the user or you just write the input. for example, if one number in the doubly linked list is 817 and in the other...
Hi, I am working on an assignment in C-Programming language dealing with LInked lists, in the...
Hi, I am working on an assignment in C-Programming language dealing with LInked lists, in the code there is instructions on where to write the code. I do not know how to write Linked Lists. Has to be in the C-language, Any help is greatly appreciated   //agelink.c //maintains list of agents //uses linked list #include <stdio.h> #include <stdlib.h> #define TRUE 1 void listall(void); void newname(void); void delink(void); void memexit(void); void wfile(void); /********************************************************************* this is the structure to hold a agent...
C++ language or Python. Linked Lists You are given a linked list that contains N integers....
C++ language or Python. Linked Lists You are given a linked list that contains N integers. You are to perform the following reverse operation on the list: Select all the subparts of the list that contain only even integers. For example, if the list is {1,2,8,9,12,16}, then the selected subparts will be {2,8}, {12,16}. Reverse the selected subpart such as {8,2} and {16,12}. The list should now be {1,8,2,9,16,12}. Your node definition should consist of 2 elements: the integer value...
(C++) All programs will be included! This lab gives you a little practice with linked lists...
(C++) All programs will be included! This lab gives you a little practice with linked lists ·Debug insertSorted() and implement sorted() in numberlist.cpp ·Hint: insertSorted() is just missing a few parts. What is in the function can work fine once you add the right code, though you are free to rewrite it ·You need to have main.cpp, numberlist.h and numberlist.cpp in this project, and if you are using Code::Blocks, remember to set the Build Options to indicate you want to...
Can you write a program for the card game WAR using linked lists in c++!
Can you write a program for the card game WAR using linked lists in c++!
With C++, 1. Assume we use two linked lists that represent Set A and Set B...
With C++, 1. Assume we use two linked lists that represent Set A and Set B respectively. Implement the following function to calculate A = A U B. Note that a SET should not contain duplicated elements (e.g., integers). void unionLL (Node * LA, Node * LB); 2. There are two linked lists, LA and LB. Their elements are both in the non-descending order. Implement the following function to merge LA and LB into a new linked list, LC. Make...
Can you write a program for snakes and ladder board game using linked lists in c++
Can you write a program for snakes and ladder board game using linked lists in c++
Write a recursive function in C++ that creates a copy of an array of linked lists....
Write a recursive function in C++ that creates a copy of an array of linked lists. Assuming: struct node { int data; node * next; }; class arrayList { public: arrayList(); ~arrayList(); private: node ** head; int size; //(this can equal 10) }
Can you program Exploding kittens card game in c++ using linked lists and classes! The game...
Can you program Exploding kittens card game in c++ using linked lists and classes! The game is played with between 2 and 4 players. You'll have a deck of cards containing some Exploding Kittens. You play the game by putting the deck face down and taking turns drawing cards until someone draws an Exploding Kitten. When that happens, that person explodes. They are now dead and out of the game. This process continues until there's only one player left, who...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT