Question

In: Computer Science

// If you modify any of the given code, the return types, or the parameters, you...

// If you modify any of the given code, the return types, or the parameters, you risk getting compile error.
// You are not allowed to modify main ().
// You can use string library functions.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#pragma warning(disable: 4996) // for Visual Studio

#define MAX_NAME 30

// global linked list 'list' contains the list of employees
struct employeeList {
   struct employee* employee;
   struct employeeList* next;
} *list = NULL;               // currently empty list

// structure "employee" contains the employee's name, room number and linked list of supervisors
struct employee {
   char name[MAX_NAME];
   unsigned int roomNumber;
   struct supervisor* supervisors;       // linked list 'supervisors' contains names of supervisors
};

// structure 'supervisor' contains supervisor's name
struct supervisor {
   char name[MAX_NAME];
   struct supervisor* next;
};

// forward declaration of functions (already implmented)
void flushStdIn();
void executeAction(char);

// functions that need implementation:
// HW 7
void addEmployee(char* employeeNameInput, unsigned int roomNumInput); // 20 points
void displayEmployeeList(struct employeeList* tempList);   // 15 points
struct employee* searchEmployee(char* employeeNameInput);   // 15 points
//HW 8
void addSupervisor(char* employeeNameInput, char* supervisorNameInput);   // 15 points
void displayEmployeeSupervisorList(struct employeeList* tempList);   // 15 points
void removeEmployee(char* employeeNameInput);           // 20 points

int main()
{
   char selection = 'a';       // initialized to a dummy value
   do
   {
       printf("\nCSE240 HW 7,8\n");
       printf("Please enter your selection:\n");
       printf("HW7:\n");
       printf("\t a: add a new employee to the list\n");
       printf("\t d: display employee list (no supervisors)\n");
       printf("\t b: search for an employee on the list\n");
       printf("\t q: quit\n");
       printf("HW8:\n");
       printf("\t c: add a supervisor of a employee\n");
       printf("\t l: display employees who report to a specific supervisor\n");
       printf("\t r: remove an employee\n");
       printf("\t q: quit\n");

       selection = getchar();
       flushStdIn();
       executeAction(selection);
   } while (selection != 'q');

   return 0;
}

// flush out leftover '\n' characters
void flushStdIn()
{
   char c;
   do c = getchar();
   while (c != '\n' && c != EOF);
}

// Ask for details from user for the given selection and perform that action
// Read the function case by case
void executeAction(char c)
{
   char employeeNameInput[MAX_NAME], supervisorNameInput[MAX_NAME];
   unsigned int roomNumInput;
   struct employee* searchResult = NULL;

   switch (c)
   {
   case 'a':   // add employee
               // input employee details from user
       printf("\nPlease enter employee's name: ");
       fgets(employeeNameInput, sizeof(employeeNameInput), stdin);
       employeeNameInput[strlen(employeeNameInput) - 1] = '\0';   // discard the trailing '\n' char
       printf("Please enter room number: ");
       scanf("%d", &roomNumInput);
       flushStdIn();

       if (searchEmployee(employeeNameInput) == NULL)   // un-comment this line after implementing searchEmployee()                  
       //if (1)                                   // comment out this line after implementing searchEmployee()
       {
           addEmployee(employeeNameInput, roomNumInput);
           printf("\nEmployee successfully added to the list!\n");
       }
       else
           printf("\nThat employee is already on the list!\n");
       break;

   case 'd':       // display the list
       displayEmployeeList(list);
       break;

   case 'b':       // search for an employee on the list
       printf("\nPlease enter employee's name: ");
       fgets(employeeNameInput, sizeof(employeeNameInput), stdin);
       employeeNameInput[strlen(employeeNameInput) - 1] = '\0';   // discard the trailing '\n' char

       if (searchEmployee(employeeNameInput) == NULL)   // un-comment this line after implementing searchEmployee()                  
       //if (0)                                   // comment out this line after implementing searchEmployee()
           printf("\nEmployee name does not exist or the list is empty! \n\n");
       else
       {
           printf("\nEmployee name exists on the list! \n\n");
       }
       break;

   case 'r':       // remove employee
       printf("\nPlease enter employee's name: ");
       fgets(employeeNameInput, sizeof(employeeNameInput), stdin);
       employeeNameInput[strlen(employeeNameInput) - 1] = '\0';   // discard the trailing '\n' char

       if (searchEmployee(employeeNameInput) == NULL)   // un-comment this line after implementing searchEmployee()                  
       //if (0)                                   // comment out this line after implementing searchEmployee()
           printf("\nEmployee name does not exist or the list is empty! \n\n");
       else
       {
           removeEmployee(employeeNameInput);
           printf("\nEmployee successfully removed from the list! \n\n");
       }
       break;

   case 'c':       // add supervisor
       printf("\nPlease enter employee's name: ");
       fgets(employeeNameInput, sizeof(employeeNameInput), stdin);
       employeeNameInput[strlen(employeeNameInput) - 1] = '\0';   // discard the trailing '\n' char

       if (searchEmployee(employeeNameInput) == NULL)   // un-comment this line after implementing searchEmployee()                  
       //if (0)                                       // comment out this line after implementing searchEmployee()
           printf("\nEmployee name does not exist or the list is empty! \n\n");
       else
       {
           printf("\nPlease enter supervisor's name: ");
           fgets(supervisorNameInput, sizeof(supervisorNameInput), stdin);
           supervisorNameInput[strlen(supervisorNameInput) - 1] = '\0';   // discard the trailing '\n' char

           addSupervisor(employeeNameInput, supervisorNameInput);
           printf("\nSupervisor added! \n\n");
       }
       break;

   case 'l':       // list supervisor's employees
       displayEmployeeSupervisorList(list);
       break;

   case 'q':       // quit
       break;

   default: printf("%c is invalid input!\n", c);
   }
}

// HW7 Q1: addEmployee (20 points)
// This function is used to insert a new employee in the linked list.
// You must insert the new employee to the head of linked list 'list'.
// You need NOT check if the employee already exists in the list because that is taken care by searchEmployee() called in executeAction(). Look at how this function is used in executeAction().
// Don't bother to check how to implement searchEmployee() while implementing this function. Simply assume that employee does not exist in the list while implementing this function.
// NOTE: The function needs to add the employee to the head of the list.
// NOTE: This function does not add supervisors to the employee info. There is another function addSupervisor() in HW8 for that.
// Hint: In this question, no supervisors means NULL supervisors.

void addEmployee(char* employeeNameInput, unsigned int roomNumInput)
{
}

// HW8 Q1: addSupervisor (15 points)
// This function adds supervisor's name to a employee node.
// Parse the list to locate the employee and add the supervisor to that employee's 'supervisors' linked list. No need to check if the employee name exists on the list. That is done in executeAction().
// If the 'supervisors' list is empty, then add the supervisor. If the employee has existing supervisors, then you may add the new supervisor to the head or the tail of the 'supervisors' list.
// You can assume that the same supervisor name does not exist. So no need to check for existing supervisor names, like we do when we add new employee.
// NOTE: Make note of whether you add the supervisor to the head or tail of 'supervisors' list. You will need that info when you implement lastSupervisor()
// (Sample solution has supervisor added to the tail of 'supervisors' list. You are free to add new supervisor to head or tail of 'supervisors' list.)

void addSupervisor(char* employeeNameInput, char* supervisorNameInput)
{

   struct employeeList* tempList = list;       // work on a copy of 'list'
  
   // YOUR CODE HERE

}

// HW8 Q2: displayEmployeeSupervisorList (15 points)
// This function prompts the user to enter a supervisor name. This function then searches for employees with this supervisor.
// Parse through the linked list passed as parameter and print the matching employee details ( name and room number) one after the other. See expected output screenshots in homework question file.
// HINT: Use inputs gathered in executeAction() as a model for getting the supervisor name input.
// NOTE: You may re-use some HW7 Q2 displayEmployeeList(list) code here.
void displayEmployeeSupervisorList(struct employeeList* tempList)
{
   // YOUR CODE HERE
}

// HW8 Q3: removeEmployee (20 points)
// This function removes an employee from the list.
// Parse the list to locate the employee and delete that 'employee' node.
// You need not check if the employee exists because that is done in executeAction()
//removeEmployee() is supposed to remove employee details like name and room number.
// The function will remove supervisors of the employee too.
// When the employee is located in the 'list', after removing the employee name and room number, parse the 'supervisors' list of that employee
// and remove the supervisors.

void removeEmployee(char* employeeNameInput)
{

   struct employeeList* tempList = list;   // work on a copy of 'list'
   // YOUR CODE HERE

}


I just need help for the HW 8 portion

Solutions

Expert Solution

//Q1


void addSupervisor(char* employeeNameInput, char* supervisorNameInput)
{
    struct employee* employeeToAdd = searchEmployee(employeeNameInput);
    /* Find the Employee to add the new supervisor to
    * Assuming that the function searchEmployee is already defined
    * Assuming that the employee already exists or else it is handled in executeAction()
    * The supervisor name given have to be added (head) to the linked list of supervisors within the employee node
    */

    struct supervisor* newsupervisor = (struct supervisor*) malloc(sizeof(struct supervisor));

    if (newsupervisor == NULL) // Failed to create a new supervisor
        return; // or Exit(-1);

    strcpy(newsupervisor->name, supervisorNameInput); // Copied data
    newsupervisor->next = employeeToAdd->supervisors; // newnode points to existing head
    employeeToAdd->supervisors = newsupervisor; // headnode changed to new node
    /*
    * Adding to headnode is preferable as it has less time complexity
    */
}

//Q2

void displayEmployeeSupervisorList(struct employeeList* tempList)
{
    char supervisorNameInput[MAX_NAME];
    printf("\nPlease enter supervisor's name: ");
    fgets(supervisorNameInput, sizeof(supervisorNameInput), stdin);
    supervisorNameInput[strlen(supervisorNameInput) - 1] = '\0';   // discard the trailing '\n' char

    struct employeeList* nextE = tempList;
    struct supervisor* nextS = 0;
    int flag;

    while (nextE != 0)
    {
        flag = 1; // not found
        nextS = nextE->employee->supervisors;
        while (flag == 1 && nextS != 0)
        {
            if (strcmp(nextS->name, supervisorNameInput) == 0)
                flag = 0; // Supervisor found
            nextS = nextS->next;
        }
        if (flag == 0)
        {
            /*
            * This output form is adopted because the sample output was not provided in the question
            */
            printf("%s of room %d\n", nextE->employee->name, nextE->employee->roomNumber);
        }
        nextE = nextE->next;
    }
    printf("Are the Employees supervised by %s\n", supervisorNameInput);
}

//Q3

void removeEmployee(char* employeeNameInput)
{
    struct employeeList* toDelete = list;   // work on a copy of 'list'
    struct supervisor* toContinue = 0;
    struct supervisor* toContinue2 = 0;

    /*
    * Assuming that the employee already exists or else it is handled in executeAction()
    */

    // If the node to delete is the head node itself
    if (strcmp(toDelete->employee->name, employeeNameInput) == 0)
    {
        toContinue = toDelete->employee->supervisors;
        list = list->next;

        free(toDelete->employee);
        free(toDelete);

        while (toContinue != 0)
        {
            toContinue2 = toContinue;
            toContinue = toContinue->next;
            free(toContinue2);
        }
        return;
    }

    struct employeeList* toDelete2 = 0;

    do
    {
        toDelete2 = toDelete;
        toDelete = toDelete->next;

        if (strcmp(toDelete->employee->name, employeeNameInput) == 0)
        {
            toContinue = toDelete->employee->supervisors;
            toDelete2->next = toDelete->next;

            free(toDelete->employee);
            free(toDelete);

            while (toContinue != 0)
            {
                toContinue2 = toContinue;
                toContinue = toContinue->next;
                free(toContinue2);
            }
            return;
        }
    } while (toDelete != 0);
}


Related Solutions

c++ /*USE STARTER CODE AT THE BOTTOM AND DO NOT MODIFY ANY*/ This is the entire...
c++ /*USE STARTER CODE AT THE BOTTOM AND DO NOT MODIFY ANY*/ This is the entire assignment. There are no more directions to it. Create an array of struct “employee” Fill the array with information read from standard input using C++ style I/O Shuffle the array Select 5 employees from the shuffled array Sort the shuffled array of employees by the alphabetical order of their last Name Print this array using C++ style I/O Random Number Seeding We will make...
Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the...
Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the code to create a function named ‘encryptECB(key, secret_message)’ that accepts key and secret_message and returns a ciphertext.          #Electronic Code Block AES algorithm, Encryption Implementation from base64 import b64encode from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Random import get_random_bytes secret_message = b" Please send me the fake passport..." password = input ("Enter password to encrypt your message: ") key= pad(password.encode(), 16) cipher...
4. Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify...
4. Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the code to create a function named ‘decryptECB(key, ciphertext)’ that accepts key and ciphertext and returns a plaintext. from base64 import b64decode from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.Padding import unpad # We assume that the password was securely shared beforehand password = input ("Enter the password to decrypt the message: ") key= pad(password.encode(), 16) ciphertext = input ("Paste the cipher...
Modify the provided code to create a program that calculates the amount of change given to...
Modify the provided code to create a program that calculates the amount of change given to a customer based on their total. The program prompts the user to enter an item choice, quantity, and payment amount. Use three functions: • bool isValidChoice(char) – Takes the user choice as an argument, and returns true if it is a valid selection. Otherwise it returns false. • float calcTotal(int, float) – Takes the item cost and the quantity as arguments. Calculates the subtotal,...
Java: modify the given example code to make it possible to create a student object by...
Java: modify the given example code to make it possible to create a student object by only specifying the name, all other info may be absent. it may also be possible to add a tag with an absent value. use OPTIONAL TYPE and NULL object design pattern.   import java.util.HashMap; import java.util.Map; public class Student { private final String aName; private String aGender; private int aAge; private Country aCountry; private Map aTags = new HashMap<>(); public Student(String pName) { aName =...
Java: modify the given example code to make it possible to create a student object by...
Java: modify the given example code to make it possible to create a student object by only specifying the name, all other info may be absent. it may also be possible to add a tag with an absent value. import java.util.HashMap; import java.util.Map; public class Student { private final String aName; private String aGender; private int aAge; private Country aCountry; private Map<String, String> aTags = new HashMap<>(); public Song(String pName) { aName = pName; } public String getName() { return...
Complete/Modify the code given in quiz3.cpp to calculate the avg and the std deviation of the...
Complete/Modify the code given in quiz3.cpp to calculate the avg and the std deviation of the array a and write the output once to myquiz3outf.txt, and another time to a file to myquiz3outc.txt. (You must write one function for the mean(avg) and one function for the std. a. For the file myquiz3outf.txt, you will use an ofstream. b. For the file myquiz3outc.txt, you will capture the cout output in a file using linux commands:./quiz3 > myquiz3outc.txt string ifilename="/home/ec2-user/environment/quizzes/numbers.txt" I've posted...
Instructions: Be sure to define all random variables, parameters, etc. Also, you must provide any code...
Instructions: Be sure to define all random variables, parameters, etc. Also, you must provide any code you use (final computed values are not sufficient). I strongly recommend that you create Jupyter Notebooks for this assignment, embedding your written comments in Markdown cells. 4. Systolic blood pressure was measured on 30 female diabetics between the ages of 30 and 34 from a particular ethnic group. Of interest is whether blood pressure, on average, of women in this population differs from the...
This program should be designed in group. Divide by classes. Parameters and return types of each...
This program should be designed in group. Divide by classes. Parameters and return types of each function and class member function should be decided in advance. Write a program that computes a patient's bill for a hospital stay. The different components are: PatientAccount Class Surgery Class Pharmacy Class main program Patient Account will keep total of the patient's charges. Keep track of the number of days spent in the hospital. Group must decide on hospital's daily rate. Surgery class will...
1- Complete/Modify the code given in quiz3.cpp to calculate the avg and the std deviation of...
1- Complete/Modify the code given in quiz3.cpp to calculate the avg and the std deviation of the array a and write the output once to myquiz3outf.txt, and another time to a file to myquiz3outc.txt. (You must write one function for the mean(avg) and one function for the std. #include<iostream> #include<string> #include<fstream> #include<cstdlib> //new g++ is stricter - it rquires it for exit using namespace std; int max(int a[],int dsize){ if (dsize>0){ int max=a[0]; for(int i=0;i<dsize;i++){ if(a[i]>max){ max = a[i]; }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT