Add a member function to Class NCLList to shuffle the elements of the list. For
ID: 3705831 • Letter: A
Question
Add a member function to Class NCLList to shuffle the elements of the list. For example, assume an instance of NCLList was being used to store a deck of cards, each card in its own node. Calling the shuffle method should produce an adequately randomized ordering of the deck of cards. We are not going to evaluate the efficacy of your shuffle algorithm. However, your algorithm does need to include randomness.
template class NCLList void inserta?eadCT ya) if (headpullrtr private: head = new Node (val); class Node else private: T data Node* next = uulius Node * temp = head; head = new Node(val, temp); public: Node(T x):data(x)) Node(T x, Node* n): data(x), next(n) ) T& getData) freturn data;3 friend class NQAUSt void print0 Node* cur = head; while(cur != uulloto Node* head; coutExplanation / Answer
#include<iostream>
using namespace std;
template<class T>
class NCList
{
private:
class Node
{
private:
T data;
Node *next = nullptr;
public:
Node(T x) : data(x) {}
Node(T x, Node *n) : data(x), next(n) {}
T& getData() { return data; }
friend class NCList;
};
Node *head;
public:
NCList()
{
head = nullptr;
}
void insertAtHead(T val)
{
if (head == nullptr)
{
head = new Node(val);
}
else
{
Node *temp = head;
head = new Node(val, temp);
}
}
void print()
{
Node *cur = head;
while (cur != nullptr)
{
cout << cur->getData() << " ";
cur = cur->next;
}
cout << endl;
}
void shuffle()
{
if (head == NULL && head->next == NULL)
return;
else
{
Node *curr = head;
Node *list1, *list2;
while (curr != NULL)
{
list1.insertAtHead(curr->data);
curr = curr->next;
if (curr != NULL)
{
list2.insertAtHead(curr->data);
}
}
shuffle(list1);
shuffle(list2);
int n = listSize(list1);
int m = listSize(list2);
int i = rand() % m;
if (m < n)
{
insertNode(i);
}
Node *curr1 = list1;
Node *curr2 = list2;
while (curr1 && curr2)
{
int coin = rand() % 2;
if (coin == 1)
{
insertElement(curr1, head);
curr1 = curr1->next;
}
else
{
insertElement(curr2, head);
curr2 = curr2->next;
}
}
if (curr1)
appendList(curr1, head);
if (curr2)
appendList(curr2, head);
removeDummy(head, i)
}
}
};
int main()
{
NCList<int> *list = new NCList<int>();
list->insertAtHead(2);
list->insertAtHead(4);
list->insertAtHead(1);
list->insertAtHead(3);
list->insertAtHead(6);
list->insertAtHead(9);
list->print();
list->shuffle();
system("pause");
return 0;
}
Please shuffle algorithm in class NCList.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.