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

ListyString *listyCat(ListyString *listy, char *str); Description: Concatenate s

ID: 3723136 • Letter: L

Question

ListyString *listyCat(ListyString *listy, char *str);
Description: Concatenate str to the end of the linked list string inside listy. If str is either NULL or the empty string (“”), then listy should remain unchanged. Be sure to update the length member of listy as appropriate.
Special Considerations: If listy is NULL and str is a non-empty string, then this function should create a new ListyString that represents the string str. If listy is NULL and str is NULL, this function should simply return NULL. If listy is NULL and str is a non-NULL empty string (“”), then this function should return a ListyString whose head member has been initialized to NULL and whose length member has been initialized to zero.
Runtime Requirement: The runtime of this function must be no worse than O(n+m), where n is the length of listy and m is the length of str.
Returns: If this function caused the creation of a new ListyString, return a pointer to that new ListyString. If one of the special considerations above requires that a NULL pointer be returned, then do so. Otherwise, return listy.

Inside H file

#ifndef __LISTY_STRING_H

#define __LISTY_STRING_H

typedef struct ListyNode

{

char data;

struct ListyNode *next;

} ListyNode;

typedef struct ListyString

{

ListyNode *head;

int length;

} ListyString;

ListyString *listyCat(ListyString *listy, char *str);

#endif

Explanation / Answer


Assuming the header file is named Listy_String.h, given below is the code for the question. Since it is not mentioned if you wanted the code in C or C++, I have given it for C.


#include <stdio.h>
#include <stdlib.h>
#include "Listy_String.h"

ListyString *listyCat(ListyString *listy, char *str)
{
ListyNode *head, *tail;
ListyNode *n;
if(str == NULL)
return listy;
else if(*str == '') //non-NULL empty string ""
{
if(listy == NULL)
{
listy = (ListyString*) malloc(sizeof(ListyString));
listy->head = NULL;
listy->length = 0;
}
}
else
{
//find the last node in listy
head = listy->head;
tail = head;
while(tail != NULL && tail->next != NULL)
tail = tail->next;
  
  
while(*str != '')
{
n = (ListyNode*) malloc(sizeof(ListyNode));
n->data = *str;
n->next = NULL;

if(tail == NULL) //is listy was initially empty string
head = tail = n;
else
{
tail->next = n;
tail = n;
}

listy->length++;
str++;

}
  
listy->head = head;
}
  
return listy;
}

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