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...
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...
Suppose you are given two circularly linked lists, L and M. Create an algorithm for telling...
Suppose you are given two circularly linked lists, L and M. Create an algorithm for telling if L and M store the same sequence of elements (but perhaps with different starting points). Please provide a main() function with it in Java to test it.
6.9 Lab: Singly-Linked Lists As an entry-level programmer you have to be able to read, understand...
6.9 Lab: Singly-Linked Lists As an entry-level programmer you have to be able to read, understand existing code and update it (add new features). One of this assignment’s goals is to read about 400 lines of code in five files, compile and run the program, understand it, and change it as required. Download and review the following files (read code and all comments carefully): College.h College.cpp LinkedList.h LinkedList.cpp main.cpp --------------------------------------------------------- //colleges.txt 3 SBCC Santa Barbara City College; 18524 97 ZZC...
Working on a c++ data structures assignment.   Linked List add node. I have the head case...
Working on a c++ data structures assignment.   Linked List add node. I have the head case and the tail case working but the middle/general case I can not get to work for the life of me. I have included the header file and the data struct file below   #ifndef LINKEDLIST_H #define LINKEDLIST_H #include "data.h" #include <iostream>   //take this out using std::cout; class LinkedList{     public:         LinkedList();         ~LinkedList();         bool addNode(int, string);         bool deleteNode(int);         bool getNode(int, Data*);         void printList(bool = false);         int getCount();         void...
Linked lists have terrible performance for random accessor searching of internal entries.Why?
Linked lists have terrible performance for random accessor searching of internal entries.Why?
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding...
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding of linked lists in C++ by creating 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!
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding...
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding of linked lists in C++ by creating 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! Using Vector or Pointer but please write a new code don't copy the one that exist before
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT