I need help fast and soon please! i am having trouble with figuring out how to w
ID: 3692289 • Letter: I
Question
I need help fast and soon please! i am having trouble with figuring out how to write this linked lists program. the following code is below and the instructions as well. this code is for C programming only please.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node {
char *name;
struct node *next;
} Node;
// function signatures
int position(char *, Node *);
Node *addEnd(char *, Node *);
// code for position goes here
//////////////////////////////////////////////////////////
Node *addEnd(char *n, Node *list) {
Node *newOne = malloc(sizeof(Node));
newOne->name = malloc(strlen(n)+1);
strcpy(newOne->name, n);
newOne->next = NULL;
if (list == NULL)
return newOne;
Node *temp = list;
while (temp->next != NULL)
temp = temp->next;
temp->next = newOne;
return list;
}
//////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
Node *list = NULL;
int a;
printf("Adding people to the list ");
for (a=1; a<argc; a++)
list = addEnd(argv[a], list);
printf("Finding positions of people in the list ");
for (a=1; a<argc; a++)
printf("%s is at position %d ", argv[a], position(argv[a], list));
printf(" Checking for people that don't exist ");
printf("Big Al is at position %d ", position("Big Al", list));
return 0;
}
Explanation / Answer
int position(char *str, Node *list) { int location = 0; // Variable to capture the index of the name Node *node = list->first; while (node->next != NULL) { // Iterate thru the list if (strlen(str) == strlen(node->data)) { // check length match before matching name int cmp = strcmp(str, node->data); // compare the input name with name in list if (cmp == 0) { // if both matches then return index of the return location; // name. } } node = node->next; location++; } return -1; // return -1 incase given name is not found in list. }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.