Question

RE-POSTED - Computer Science staff, I need this question answered. It will determine a pass or a fail. Its very imortant that this and the other questions posted are answered 100% Thank you.

13 - Template C++ Advance

Please Only answer assignment if your code is 100%. When pasteing your code use text so I may copy and paste into visual studio. The code and questions must be answered 100% correct and works. Thank you.

Find the error(s) in the following code: (8, 9) template <class type> class strange 33. //Line //Line 2 Hi strange<int> sl; strange( type> s2; //Line 3 //Line 4

Programming Assignment

Convert the int linked list class to a template class. Use attached files: LinkedList.h and LinkedList.cpp.

Test your linked list template by writing a test program that creates an int linked list and a string linked list, and uses each of the LinkedList methods at least once.

LinkedList.cpp

// Implementation of the LinkedList class

//#include "Stdafx.h"
#include "LinkedList.h"
#include <string>
#include <iostream>

using namespace std; //needed for cout, cin to be recognised

// Default constructor
LinkedList::LinkedList(){
   head = NULL;
   size = 0; //Don't forget to do this!!!
}

/* Copy constructor to copy an existing list. Note that the compile
* will generate a copy constructor automatically. However, this
* constructor only creates a SHALLOW COPY (so would only copy the
* size and head variables). In this case this would NOT CREATE A
* NEW LIST, just a new reference to one list. It is therefore
* necessary to write a constructor that makes a DEEP COPY.*/

/* Also note the parameter. C++ functions use pass-by-value by
* default. This means that the functions make copies of the given
* arguments. This is inefficient (particularly for large objects).
* Therefore it is normal to pass the address (using &) of the parameter,
* but, if the parameter should not be changed, it is good practice to
* make it const, which prevents it from being changed.*/
LinkedList::LinkedList(const LinkedList& lst){
   if (lst.head == NULL){
       head = NULL;
       size = 0;
   }
   else{
       // Copy first node and assign head
       /* OK, what's with the '->'? The -> operator accesses the attribute
       * or method of the object (or struct) that is refererred to by a
       * pointer. So "head -> data" is the contents of the data variable
       * of the object that head points to. Note that this is synonomous
       * with "(*head).data" but the latter syntax is ugly and confusing and
       * is therefore rarely used. */
       head = new Node;
       head->data = lst.head->data;
       /* Now copy the rest of the list. To do this we'll need to create two
       * temporary pointers, one to go through the old list, one node at a
       * time, and one to keep pace in the new list, creating new nodes. */
       Node *pNewNode = head;
       Node *pOldNode = lst.head->next;
       // Repeat until the entire list is copied
       while (pOldNode != NULL){
           pNewNode->next = new Node;
           pNewNode = pNewNode->next;
           pNewNode->data = pOldNode->data;;
           pOldNode = pOldNode->next;
       }
       pNewNode->next = NULL;
       size = lst.size;
   }
}

/* The destructor is responsible for deleting any memory that was dynamically
* allocated by an object. If there is no such memory no destructor needs to
* be created (the compiler automatically creates one). Because this class
* uses pointers to create new Nodes it is necessary to write a destructor.
* Destructors are identified by the '~' preceding the class name. There can
* be only one destructor for a class, and it cannot have parameters. */
LinkedList::~LinkedList(){
   removeAll();
}

/**************************************************************************/
// LinkedList Operations

// Adds a node to the start of the list, making it the new head
void LinkedList::add(int x){
   Node *p = new Node; //temporary node
   // Assign appropriate values to the new node
   p -> data = x;
   p -> next = head;
   // Make the head point to the new node
   head = p;  
   size++;
}

// Inserts a new node at the given position (or index) in the list
void LinkedList::insertAt(int pos, int x){
   Node *p;
   Node *newNode;
      
   // Check that pos is a valid index
   if (pos <= size){
       newNode = new Node; //new node
       newNode->data = x;

       // Deal with case when item is to be inserted at the head of the list
       if (pos == 0){
           newNode->next = head;
           head = newNode;
       }// if(pos == 0)
       else{
           p = head;
           // Move to position BEFORE insertion point
           for(int i = 0; i < pos-1; i++){
               // Check that p points to a node
               // Note using exception handling should throw an exception here
               if(p == NULL){
                   return;
               }
               p = p->next;
           }//for
           // Insert node
           newNode->next = p->next;
           p->next = newNode;
       }//else (pos != 0)
       size++;
   }//else (pos >= size) do nothing
}

// Removes the first node containing the given data, returns true
// iff data is found (and deleted).
bool LinkedList::remove(int x){
   Node *p = head;
   Node *temp;
   // Check to see if the list exists
   if (head == NULL){
       return false;
   }
   // Check to see if target is at the head of the list
   else if (head->data == x){
       head = head->next;
       delete p; //currently assigned head
       size--;
       return true;
   }
   // Otherwise iterate through list
   else{
       while(p->next != NULL){
           // Check next node for target
           if(p->next->data == x){
               temp = p->next;
               p->next = p->next->next;
               size--;
               delete temp;
               return true;
           }
           p = p->next;
       }
   }
   return false;
}

// Empties the list by deleting each node, starting at the head
void LinkedList::removeAll(){
   Node *p = head;
   // Traverse the list deleting nodes
   while (p!= NULL){
       head = head->next; // Mustn't "lose" the next node
       delete p; // De-allocate memory
       p = head; // Go to next node
   }
   head = NULL;
   size = 0;
}

// Prints the entire list (head first) to the screen.
/* Note that there is some debate about whether or not this type of
* method belongs in a class. The argument (briefly) is that a class
* shouldn't be responsible for its own display as it cannot foresee
* how it is to be displayed. */
void LinkedList::printList(){
   Node *p = head;
   cout << "["; //Nice format!
   // Traverse the list
   while (p != NULL){
       cout << p -> data; // Print data
       p = p -> next; // Go to next node
       if (p != NULL){
           cout << ","; // Print a comma unless at the end of the list
       }
   }
   cout << "]"; // Don't print a newline - it might not be wanted
}

LinkedList.h

// Header file for linked list class

class LinkedList{
public:
   // Constructors and Destructors
   /* Generally every class should have at least two construtors, a
   * default constructor and a copy constructor that creates a copy
   * of the given object*/
   LinkedList(); //default construtor
   LinkedList(const LinkedList& lst); //copy constructor
   /* Every class should have a destructor, which is responsible for
   * cleaning up any dynamic memory allocation performed by the class.
   * Note the special syntax for the destructor */
   ~LinkedList();//destructor
  
   // PRE:
   // POST: A new node containing the given data is inserted at the front
   // of the list
   // PARAM: data is the data to be stored
   void add(int data);

   // PRE:
   // POST: A new node containing the given data is inserted at the given
   // position in the list
   // PARAM: pos specifies the (index) position to insert the new node
   // data is the data to be stored
   void insertAt(int pos, int data);
  
   // PRE:
   // POST: The first incidence of the given data is removed from the list.
   // Returns true if data is found (and removed), false otherwise
   // PARAM: data specifies the data to be removed from the list
   bool remove(int data );
  
   // PRE:
   // POST: Empties the list, freeing up dynaically allocated memory
   // PARAM:
   void removeAll();

   // PRE:
   // POST: Prints the contents of the list to the screen, in order
   // PARAM:
   void printList();

private:
   /* A struct contains data variable (which are accessed using dot
   * notation in the same way that object methods or attributes are
   * accessed). Structs cannot have methods.*/
   // List node
   struct Node {
       int data; //list data
       Node *next; //pointer to next item in the list
   };

   Node *head; //Pointer to the first node in the list
   int size; //Records the number of nodes in the list
};

template_test.cpp

#include "LinkedList.h"


#include <iostream>
using namespace std;


int main()
{

   //Add your test code here
  
   system("pause");
   return 0;

}

Resources that help:

Creating a Template

C++ allows a programmer to create templates that can be instantiated. A template allows objects to be created that can store (or use) data of any type.

In this lab you will convert the int linked list class to a template class. Use attached files:

LinkedList.h

LinkedList.cpp

To convert the class to a template class you must:

Put the entire class (the .h file class definition, and the .cpp file method implementations) in one .h file. For this lab, put the entire class into LinkedList.h

Preface the template class definition and each template member function implementation with this line: template <class Type>

The class qualifier (LinkedList::) that appears before a method name in each implementation, should be replaced by LinkedList<Type>::

Whenever the type that the class contains (int in our case) is referred to it should be replaced with the word Type

For example here is the add method before and after these changes:

void LinkedList::add(int x){
       Node *p = new Node; //temporary node
       // Assign appropriate values to the new node
       p -> data = x;
       p -> next = head;
       // Make the head point to the new node
       head = p;     
}

and the "templated" version

template <class Type>
void LinkedList<Type>::add(Type x){
       Node *p = new Node; //temporary node
       // Assign appropriate values to the new node
       p -> data = x;
       p -> next = head;
       // Make the head point to the new node
       head = p;     
}

To use your linked list template class in a program you need to specify what type is to be stored:

LinkedList<int> creates a linked list of ints, and

LinkedList<string> creates a linked list of strings

Testing

Test your linked list template by writing a test program in template_test.cpp that creates an int linked list and a string linked list, and uses each of the LinkedList methods at least once.

Additional Resource

https://www.youtube.com/watch?v=gefYtPeLB7o

0 0
Add a comment Improve this question Transcribed image text
Request Professional Answer

Request Answer!

We need at least 10 more requests to produce the answer.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the answer will be notified once they are available.
Know the answer?
Add Answer to:
RE-POSTED - Computer Science staff, I need this question answered. It will determine a pass or...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should h...

    Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member function for inserting an item in the list, deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found. In addition, it should member functions to display the list, check if...

  • In C++, for the provided template linked list class create a derived class of it which...

    In C++, for the provided template linked list class create a derived class of it which adds the functionality to it to find the high and low value of any given data stored in the list. The derived class must be a template. LinkedList.h #pragma once #include <iostream> using namespace std; template <class T> class ListNode {    public:        T data;        ListNode<T>* next;        ListNode(T data)        {            this->data = data;...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how...

    Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how to get size. I'm not sure. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = 0; } /* Constructor */ public Node(int d, Node n, Node p) { data = d; next = n; prev = p; } /* Function...

  • Introduction In this lab, you are supposed to implement a graph class with the data structure...

    Introduction In this lab, you are supposed to implement a graph class with the data structure implemented before like linked list and queue. graph The class graph contains three member variables: linkedList *adjacentVertices; //an array of linked list. For a vertice i, adjacentVertices[i] stores the linked list that contains all other vertices connected to vertice i. int numVertices; //The number of vertices in the graph. int maxNumVertices; //The maximum number of vertices the graph can hold. Following public methods are...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include...

    BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include the method to delete a node from the Linked List. In summary: 1) Add the method Delete 2) Method call to delete, with a number that IS in the list 3) Method call to delete, with a number that is NOT in the list - Be sure to include comments - Use meaningful identifier names (constants where appropriate) import java.io.*; 1/ Java program to...

  • #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ...

    #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ListNode *head; class LinkedList { public: int insertNode(float num); void deleteNode(float num); void destroyList(); void displayList(); LinkedList(void) {head = NULL;} ~LinkedList(void) {destroyList();} }; int LinkedList::insertNode(float num) { struct ListNode *newNode, *nodePtr = head, *prevNodePtr = NULL; newNode = new ListNode; if(newNode == NULL) { cout << "Error allocating memory for new list member!\n"; return 1; } newNode->value = num; newNode->next = NULL; if(head==NULL) { cout << "List...

  • Q) Modify the class Linked List below to make it a Doubly Linked List. Name your...

    Q) Modify the class Linked List below to make it a Doubly Linked List. Name your class DoublyLinkedList. Add a method addEnd to add an integer at the end of the list and a method displayInReverse to print the list backwards. void addEnd(int x): create this method to add x to the end of the list. void displayInReverse(): create this method to display the list elements from the last item to the first one. Create a main() function to test...

  • **HELP** Write a function that takes a linked list of items and deletes all repetitions from the ...

    **HELP** Write a function that takes a linked list of items and deletes all repetitions from the list. In your implementation, assume that items can be compared for equality using ==, that you used in the lab. The prototype may look like: void delete_repetitions(LinkedList& list); ** Node.h ** #ifndef Node_h #define Node_h class Node { public: // TYPEDEF typedef double value_type; // CONSTRUCTOR Node(const value_type& init_data = value_type( ), Node* init_link = NULL) { data_field = init_data; link_field = init_link;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT