Question

In: Computer Science

Write a program using C to read a list of your friend names which ends by...

Write a program using C to read a list of your friend names which ends by the word end. The program builds a linked list using these names and prints the names in the order stored into the linked list The list can be created using insertion at the beginning or insertion at the end; Use switch case to select the type of insertion;

Case 1:insertion in the beginning;

Case2:insertion in the end.

Once the list is printed after insertion; count the total number of names(nodes) in the link list and then,remove the name from the list (entered by the user at run time) and then print the list and count of nodes.

Solutions

Expert Solution

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

typedef struct Node Node;

struct Node {
    char* name;
    struct Node* next;
};

Node* head = NULL;
Node* curr = NULL;
Node* prev = NULL;
int count = 0;

void listAdd(char* word, bool toEnd)
{
    Node* temp = head;
    curr = head;

    // point temp to the end
    while (temp != NULL && temp->next != NULL)
        temp = temp->next;

    //create new node
    Node* ptr = (Node*)malloc(sizeof(Node));
    ptr->name = (char*)malloc(strlen(word) + 1);
    strcpy(ptr->name, word); //store the word
    ptr->next = NULL;

    if (head == NULL) //if list is empty
    {
        head = ptr;
        count++;
        return;
    }

    if (toEnd) //if adding to the end
    {
        //temp is pointing to the end node
        temp->next = ptr; //attach new node to the end
        count++;
    }
    else //if adding to the start of list
    {
        ptr->next = head; //attach new node at the start
        head = ptr; //now new node becomes head
        count++;
    }
}

void readWord(bool flag)
{
    char buffer[100]; //to hold the name
    printf("\nType end to stop:");

    //read till end is typed
    while (true) {
        printf("\nEnter the name: ");
        scanf("%s", buffer);

        if (strcmp(buffer, "end") == 0) //if user types end
            break; // stop adding to the list

        listAdd(buffer, flag); //add the name
    }
}

void remove_name(char* data)
{

    if (head == NULL) {
        printf("List is empty");
        return;
    }

    if (strcmp(head->name, data) == 0) {
        //if name to be deleted is at the start

        if (head->next != NULL) {
            //and there are more than 1 names
            head = head->next; //remove the first
            count--;
            return;
        }
        else {
            //and there is only one name in list i.e only head
            head = NULL;
            count--;
            printf("List is empty now");
            return;
        }
    }
    else if (strcmp(head->name, data) != 0 && head->next == NULL) {
        //if there is only one node(head) and its name doesn't match
        printf("\n***** %s not found in the list! \n", data);
        return;
    }

    curr = head;

    while (curr->next != NULL && strcmp(curr->name, data) != 0) {
        //loop and find name in the list start to end
        //stop if name is found by curr->name
        prev = curr;
        curr = curr->next;
    }

    if (strcmp(curr->name, data) == 0) {
                //if name is found in list (eg. A B C)
                //if B is to be removed then point A->next to the B-next i.e C
                //thus removes B        
        prev->next = curr->next; 
        //prev->next = prev->next->next;  //this also can be used
        count--;
        free(curr);
    }
    else
        printf("\n***** %s not found in the list! \n", data);
}

void printList()
{
    Node* ptr = head;
    printf("\n--------Friend List--------\n");
    
    while (ptr) {
        printf("%s  ", ptr->name);
        ptr = ptr->next; //set ptr to next node
    }
    printf("\ncount = %d  ", count);
}

void freeList()
{
    Node* ptr = head;
    Node* tmp = 0;
    //loop through the list and free each node
    while (ptr) {
        tmp = ptr->next;
        free(ptr->name);
        free(ptr);
        ptr = tmp;
    }
}

int main(void)
{
    int option = 0;
    char buffer[100];

    printf("\n1. Insertion in the beginning");
    printf("\n2. Insertion at the end");
    printf("\nSelect your option: ");
    scanf("%d", &option);
    
    if (option == 1) {
        readWord(false);
    }
    else if (option == 2) {
        readWord(true);
    }
    else {
        printf("\n*** Invalid option!!!");
    }
    printList();
    
    printf("\nEnter name to remove: ");
    scanf("%s", buffer);
    
    remove_name(buffer);
    
    printList();
    freeList();
    return 0;
}

Output------------------


Related Solutions

Using OOP, write a C++ program that will read in a file of names. The file...
Using OOP, write a C++ program that will read in a file of names. The file is called Names.txt and should be located in the current directory of your program. Read in and store the names into an array of 30 names. Sort the array using the selection sort or the bubblesort code found in your textbook. List the roster of students in ascending alphabetical order. Projects using global variables or not using a class and object will result in...
Using LIST and FUNCTION Write a program in Python that asks for the names of three...
Using LIST and FUNCTION Write a program in Python that asks for the names of three runners and the time it took each of them to finish a race. The program should display who came in first, second, and third place.
Client AND server using names pipes (mkfifo) in C/C++ Write and client program that will talk...
Client AND server using names pipes (mkfifo) in C/C++ Write and client program that will talk to a server program in two separate terminals. Write the server program that can handle multiple clients (so threads will be needed) and with fork() and exec()
Write a program in python to read from a file the names and grades of a...
Write a program in python to read from a file the names and grades of a class of students to calculate the class average, the maximum, and the minimum grades. The program should then write the names and grades on a new file identifying the students who passed and the students who failed. The program should consist of the following functions: a) Develop a getGrades() function that reads data from a file and stores it and returns it as a...
Write a C++ program to read in a list of 10 integers from the keyboard. Place...
Write a C++ program to read in a list of 10 integers from the keyboard. Place the even numbers into an array called even, the odd numbers into an array called odd, and the negative numbers into an array called negative. Keep track of the number of values read into each array. Print all three arrays after all the numbers have been read. Print only the valid elements (elements that have been assigned a value). a. Use main( ) as...
Write a C++ program using dynamic arrays that allows the user to enter the last names...
Write a C++ program using dynamic arrays that allows the user to enter the last names of the candidates in a local election and the number of votes received by each candidate. The program must ask the user for the number of candidates and then create the appropriate arrays to hold the data. The program should then output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should...
PROBLEM STATEMENT: Using the list container from the STL, write a program that will read the...
PROBLEM STATEMENT: Using the list container from the STL, write a program that will read the information from a file into a list and then display the list to the screen. Add your name. Sort the list by id. Print the list again CODE: Use the provided disneyin2.txt file. Do not hard code the file name; get file name from user. Use the struct below struct student { char firstnm[20], lastnm[20]; int id, grade; }; You are to create a...
Write in C++ Write a program that accepts the names of three political parties and the...
Write in C++ Write a program that accepts the names of three political parties and the number of votes each received in the last mayoral election. Display the percentage of the vote each party received.   Be sure to provide labels (party name) and number-align your output values.
C++ in one program that ends with return 0} at the end f Write a program...
C++ in one program that ends with return 0} at the end f Write a program to calculate the salary paid to its salespersons at Pohanka. The salary is calculated based on a salesperson’s length of employment in years and employment category (full-time employee or part-time employee). The salary calculation rules are as following: 1) If an employee is a part-time employee and worked here for less than 5 years, the salary consists of only the commission amount; 2) If...
using c++. ALWAYS GRADE MY ANSWERS Write a program that reads students’ names followed by their...
using c++. ALWAYS GRADE MY ANSWERS Write a program that reads students’ names followed by their test scores. The program should output each student’s name followed by the test scores and the relevant grade. It should also find and print the highest test score and the name of the students having the highest test score. Student data should be stored in a struct variable of type studentType, which has four components: studentFName and studentLName of type string, testScore of type...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT