0

I hope you can help me, It's really important. Please I have a program which I need to print a name 23 times char by char using linked lists. I have made it work printing it once, even though I have a for loop I can't make it print the text 23 times. Please help. I don't know where to start.

You would really help me a lot by answering this question, I've tried a lot but im still not able to understand how to do it. Thanks in advance.

#include <conio.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> typedef struct L { char c; struct L *next; }List; List *l = NULL; // list head, we'll prepend nodes here int c; // variable for current read character List *getInput(void) { while ((c = getchar()) != '\n') { // read until enter List *n = calloc(1, sizeof(List)); // create new list node n->c = c; // store read character in that node n->next = l; // prepend newly created node to our list l = n; // store newly created node as head of list } return l; } int main ( void ) { printf("Ingresa tu nombre.\n"); getInput(); printf("\n"); int i = 0; for(i;i<23; //I tried something like l=1; here bit it didn't work. while (l != NULL) { // while we have not reached end of list putchar(l->c); // print character stored in list printf("\n"); l = l->next; // and advance to next list node } } return 0; } 
3
  • Remove the for loop, if the list has 23 nodes then the while loop will iterate 23 times. Commented Nov 6, 2018 at 0:44
  • I need that the code inside the while repeats 23 times, No matter how many nodes i have. Commented Nov 6, 2018 at 0:46
  • oh, well maybe move printf("\n") out of and after the while loop. Commented Nov 6, 2018 at 0:47

1 Answer 1

2

You need to start at the beginning of the list each time through the for loop. This means you must not overwrite the the variable l that points to the beginning of the list. Instead, use a different variable for iterating.

int main ( void ) { printf("Ingresa tu nombre.\n"); getInput(); printf("\n"); int i = 0; for(i;i<23;i++){ List *cur = l; while (cur != NULL) { // while we have not reached end of list putchar(cur->c); // print character stored in list printf("\n"); cur = cur->next; // and advance to next list node } } return 0; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It was just what I needed. You saved me, Literally.