[ back to toc ]

Linked Lists in C

Date: 2001/12/06 20:33

Q:
Hello, i'm new to C, i am trying to implement a linked list, so that when
you input a word, you are able to print out the phrase you typed in in
reverse. I have set up the linked list! (I think) and i use getchar to
gather the phrase. I am attempting to use a for loop to go through the
list and print out the values in it one by one, as they ahould be in
reverse order. However what i have done does not work, it doesn't seem to
link with the list: here is what i have got so far:

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

/*definition of list*/

typedef struct L {char x; struct L *next;} list;

/*memory allocation using calloc*/

list *insert(char h, list *t){

list *y = calloc( 1, sizeof( list ));
y->x = h; y->next = t;
return y;

}

int
n(){

list *z = NULL;
char a;
printf("please type in sentence\n");

while((a = getchar()) != '.'){
z=insert (a, z);

}
for( z; z != NULL; z++)

printf("%s\n", z);
}


I am pretty sure that the list structure has been set up correctly, and that the getchar works fine! I'm sure my problems lie within the way i have done my for loop.
any help you could give would be very much appreciated! thankyou!!!

*NAME-DELETED* *NAME-DELETED*

A:
list *insert(char h, list *t){

list *y = calloc( 1, sizeof( list ));
y->x = h; y->next = t;
return y;

}

is wrong. The list has to be altered as well.

list *insert(char h, list **t){

list *y = calloc( 1, sizeof( list ));
y->x = h; y->next = *t;
*t = y;
return y;
}

is the correct function. After this there are some other problem:

for( z; z != NULL; z++)

???
Why there is 'z' on the first expression? Omit it. And you can not z++ to step to the next element. Instead:

for( ; z ; z=z->next );

And do not forget that the call to function insert has to be altered as well.

Regards,
Peter

[ back to toc ]