In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of November 9th
(this exercise will still be available for submission after that deadline, but without couting towards your grade)
[to understand the context of this problem, you should read the class #05 exercise sheet]


[AED024] Duplicating elements

In this problem you should only submit a singlyLinkedList.h file with a self-containing definition of a class SinglyLinkedList<T>

Base Code

Use as a basis the class SinglyLinkedList<T> (see code | download code) which implements a generic singly linked list similar to what was done on classes, with methods to add and remove an element in the end, return the size, knowing if the list is empty or printing the list.

The Problem

Add a new method void duplicate() to the class. The function should duplicate all elements. For instance, the list {1,2,3} should become {1,1,2,2,3,3} and the list {'a','b'} should become {'a','a','b','b'}.

Submission

You should submit the file singlyLinkedList.h with the method duplicate added to SinglyLinkedList<T> as requested (and without removing any of the other existing methods). You can however create additional methods, if you need them.

Mooshak will use the following code to link to your class, read the inputs, build the lists and call your method, printing its result.

#include <iostream>
#include <string>

#include "singlyLinkedList.h"

// Read n and then n elements to add to the list using addFirst, followed by
// a call to duplicate
template <typename T>
void read() {
  int n;
  std::cin >> n;
  SinglyLinkedList<T> lst;
  for (int i=0; i<n; i++) {
    T v;
    std::cin >> v;
    lst.addFirst(v);
  }
  std::cout << "lst = " << lst.toString() << " | size = " << lst.size() << std::endl;  
  lst.duplicate();
  std::cout << "lst = " << lst.toString() << " | size = " << lst.size() << std::endl;
  std::cout << "-------------------------" << std::endl;
}

int main() {

  int n;
  std::cin >> n;
  for (int i=0; i<n; i++) {
    std::string type;
    std::cin >> type;
    if (type == "int") read<int>();
    else if (type == "char") read<char>();
    else if (type == "string") read<std::string>();
  }
  
  return 0;
}

Example Input Example Output
4

int 3
3 2 1

char 2
b a

string 4
cool very is programming

int 0

lst = {1,2,3} | size = 3
lst = {1,1,2,2,3,3} | size = 6
-------------------------
lst = {a,b} | size = 2
lst = {a,a,b,b} | size = 4
-------------------------
lst = {programming,is,very,cool} | size = 4
lst = {programming,programming,is,is,very,very,cool,cool} | size = 8
-------------------------
lst = {} | size = 0
lst = {} | size = 0
-------------------------


Algorithms and Data Structures (L.EIC011) 2024/2025
DCC/FCUP & DEI/FEUP - University of Porto