Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "circularlyLinked.h"
- circularlyLinked::circularlyLinked(vector<string> &uniqueNames) {
- numberOfPeople = 1; //starts from one because the head counts as a person.
- head = new Node;
- Node *q = head;
- head -> name = uniqueNames[0];
- for(int i=1; i<uniqueNames.size(); i++) { //Defines the total number of people and creates the linked list
- q->next = new Node;
- q = q->next;
- q->name = uniqueNames[i];
- numberOfPeople++;
- }
- q->next = head; //This statement makes the linked list into a circularly linked list.
- }
- void circularlyLinked::josephus(int m, ofstream &out_str) {// function which goes through the circularlyLinkedList of Nodes and removes every mth Node. It prints out his/her name.
- Node *p = head;
- Node * q;
- while(numberOfPeople > 1)
- {
- if(m==1) //When m=1, it is a special case because of the way the erase function works.
- {
- p = head;
- removedNames.push_back(head->name); //Adds the name of the person to the vector of removedNames.
- head = head->next;
- delete p;
- }
- else { //When m!=1, every mth Node is removed. The name of each node is then added to the removedNames vector.
- for(int i=1; i<m-1; i++)
- p = p->next;
- removedNames.push_back(p->next->name);
- q = p->next;
- p->next = p->next->next;
- delete q;
- p = p->next;
- }
- numberOfPeople--; //Decreases number of people every time someone dies.
- }
- out_str << "circular list\nsurvivor: " << p->name << endl;
- }
- void circularlyLinked::printRemovedPeople(int m, ofstream &out_str) { //Prints out the names of those who did not survive.
- out_str << "removed:\n";
- int totalSize = removedNames.size();
- for(int i=1; i<=totalSize; i++){ //
- out_str << " " << i << ": " << removedNames.front() << endl;
- removedNames.erase(removedNames.begin());
- }
- out_str << "==========" << endl;
- }
Add Comment
Please, Sign In to add comment