Linked Lists in C

Associate
Joined
18 Mar 2007
Posts
291
Hi guys, having a bit of trouble with my printlist function (it prints out all 1's, instead of the values that i enter):

Code:
#include <stdlib.h>
#include <stdio.h>

typedef struct L {
	int data;
	struct L *next;
} list;

list *insertList( int hd, list *tl ) {
	list *t = malloc( sizeof( list ) ) ;
	t->data = hd ;
	t->next = tl ;
	return t ;
}

list *somelist( void ) {
	list *h = NULL ;
	int i=1;
	int c;
	while(c=getchar()!='.') {
		h=insertList( c, h );
		i++;
	}
	return h ;
}

void printlist(list *head) {
     int i;
     list *current = head;
     
     while(current!=NULL) {
        printf("%d", current->data);
		current=current->next;
	}	
}

int length(list *head) {
	list *current = head;
	int count = 0;
	while (current != NULL) {
		count++;
		current = current->next;
	}
	printf("%d\n", count);
	return count;
}

int main(void) {
	
	
	list *z=somelist();
	length(z);
	printlist(z);
	
	return 0;
}

So if i input:
Code:
12345
.

The output will be:
Code:
5
11111

Any help would be great.

Cheers, Rob
 
Forgive me as it's been awhile since I've done C but should
Code:
current=current->next;
be
Code:
current=current.next;
as it's a struct you are accessing not an object.
 
Code:
list *somelist( void ) {
	list *h = NULL ;
	int i=1;
	int c;
	while([B][COLOR="Red"]c=getchar()!='.'[/COLOR][/B]) {
		h=insertList( c, h );
		i++;
	}
	return h ;
}

You need to put parentheses around c = getchar(). What it's currently doing is evaluating getchar() != '.' and assigning the result – which is 1 as long as you don't input a period – to c.

Forgive me as it's been awhile since I've done C but should
Code:
current=current->next;
be
Code:
current=current.next;
as it's a struct you are accessing not an object.

Nope, because current is a pointer, so the -> operator is needed to dereference it.
 
Code:
list *somelist( void ) {
	list *h = NULL ;
	int i=1;
	int c;
	while([B][COLOR="Red"]c=getchar()!='.'[/COLOR][/B]) {
		h=insertList( c, h );
		i++;
	}
	return h ;
}

Hey, that works, but it still doesn't print out the right result.

It prints out:

Code:
Input: 1.
Output: 49

Input: 1
         .
Output: 1049

Input: 2.
Output: 50

Any ideas?
 
edit: beaten :p

That's because you're storing them and displaying them as integers.

What you need to do instead is either store them as characters or convert them to just before displaying them:

Code:
typedef struct L {
	[COLOR="Red"][B]char[/B][/COLOR] data;
	struct L *next;
} list;

/* snip */

void printlist(list *head) {
	int i;
	list *current = head;
	
	while(current!=NULL) {
		printf("[COLOR="Red"][B]%c[/B][/COLOR]", current->data);
		current=current->next;
	}	
}

…or…

Code:
while(current!=NULL) {
	printf("[COLOR="Red"][B]%c[/B][/COLOR]", [COLOR="Red"][B](char)[/B][/COLOR]current->data);
	current=current->next;
}
 
Back
Top Bottom