user3221699 user3221699 - 3 months ago 6
C Question

Iterating over linked list and adding new value

I am new to the topic of linked list and having a hard time figuring how to add a 'u' after every 'o' the user enters. Any help or assistance is greatly appreciated.

The programs input:


./queensenglish

Input string?:

i love the color yellow


The program's expected output:


Charlatan! I use the Queen’s English:

i louve the coulour yellouw


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

typedef struct node
{
char myChar;
struct node* next;
} node;

node* stringToList(char* inputString)
{
node* first = malloc(sizeof(node));
first->myChar = 'a';
first->next = NULL;
node* current = first;

char* s;
for(s = inputString; *s != '\0'; s++)
{
node* newNode = malloc(sizeof(node));
newNode->myChar = *s;
newNode->next = NULL;
current->next = newNode;
current = newNode;
}
return first->next;
}

char* listToString(node* firstChar)
{
// get the length of the string
int totalLen = 0;
node* current = firstChar;
while(current != NULL)
{
totalLen++;
current = current->next;
}

char *newString = malloc(sizeof(char)*(totalLen+1));
char *iter = newString;
current = firstChar;
for (int i = 0; i < totalLen; i++)
{
*iter = current->myChar;
current = current->next;
iter++;
}
*iter = '\0';
return newString;
}

int main(void)
{
// Read in an input string
printf("Input string?: \n");
char* myString = GetString();

// Convert that string into a linked list
node* firstChar = stringToList(myString);

node* current = firstChar;
while(current != NULL){

if(strcmp(&current->myChar, "o") == 0 || (strcmp(&current->myChar, "O") == 0)
{
//insert a 'u' after every 'o'
//printf("Char: %c\n", current->myChar);
}
current = current->next;
}

// convert the list back into a string
char* newString = listToString(firstChar);

// print out the "corrected" string
printf("Charlatan! I use the Queen's English:\n");
printf("%s\n", newString);
}

Answer
if(current->myChar == 'o' || current->myChar == 'O')
{
    node *insertNode = malloc(sizeof(node));
    insertNode->myChar = 'u';
    insertNode->next = current->next;
    current->next = insertNode;
    current = current->next;//skip 'u' node
}