Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A list of strings is built using the following struct: struct node { char * data

ID: 3607631 • Letter: A

Question

A list of strings is built using the following struct:
struct node {
  char * data;
  struct node * next;
};
Assume that the list (if non-empty) is sorted alphabetically. That is, the strings in the data nodes are sorted such that each element is less than (according to strcmp) the next element in the list.
Define a function named insertString that creates a new node and adds it to the list, in the correct order. The first argumentis a list, and the second argument is a string (char *). You do not need to copy the string -- just point to it in the new node that you create. The return value is the head of the new list.
You may use strcmp() to compare strings, and you may assume that all necessary header files have been included.

Explanation / Answer

//insertString function takes two param

// head node and string

// it compare the string and insert at suitable position

void insertString(struct node **head, char * str) {

struct node *temp = *head;

struct node *prev = *head;

// creating new Node

struct node *newNode = (struct node*)malloc(sizeof(struct node));

newNode->data = str;

// Memory allocated to node or not

if (newNode == NULL) {

printf("Memory Not allocated ");

return;

}

// if first node is head node

// if str value small then head node string value

if (*head == NULL || strcmp((*head)->data, str) > 0) {

newNode->next = *head;

*head = newNode;

}

else {

while (temp != NULL) {

if (strcmp(temp->data, str) > 0) {

break;

}

prev = temp;

temp = temp->next;

}

if (temp == NULL) {

newNode->next = temp;

}

else {

newNode->next = temp->next;

}

prev->next = newNode;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote