Re: Problem with a linked list
- From: websnarf@xxxxxxxxx
- Date: 8 May 2005 12:14:26 -0700
Xarky wrote:
> I am writing a linked list in the following way.
>
> struct list
> {
> struct list *next;
> char *mybuff;
> };
>
> struct list *myList = NULL;
> struct list *endList = NULL;
>
> void getline(char s[], int lim)
> {
> int c, i;
>
> for(i=0; ((i<lim-1) && ((c=getchar()) != '\n')); i++)
> s[i] = c;
>
> s[i] ='\0';
> } // end method getline
"//" is not a portable way of expressing a comment in C. Not that
portability is an issue in this newsgroup. (You can also use fgets()
as an alternative to the function you've written.)
Ok, to the issue of linked lists.
1. First of all, you have to remember to allocate individual storage
for each string that you input. If you reuse the same buffer for
input, then your older input will simply be overwritten by it each
time.
2. Ok, there is also a common obfuscation that people do when they make
linked lists of distinguishing the "empty list" case from the other
cases. Actually both cases are the same if you think of the "current
tail pointer" as a reference to the link point, rather than the upper
container of the link point. I.e., tail should be &("last"->next)
rather than just "last". In this way the "current tail pointer" for
empty list is just the address of the top-of-list pointer, and is just
the address of the last "->next" record in the list.
I've demonstrated this in the code below:
static char * copystr (const char * data) {
int l = strlen(data) + 1;
char * s = (char *) malloc (sizeof (char) * l);
if (s) memcpy (s, data, l);
return s;
}
struct list ** add_item (struct list ** tail, char * data) {
if (NULL == tail ||
NULL != *tail ||
(NULL == (*tail = (struct list *) malloc(sizeof(struct list))))
)
return NULL;
(*tail)->mybuff = copystr (data);
(*tail)->next = NULL;
return &((*tail)->next);
}
void printlist (struct list * head) {
while (head) {
printf ("%s\n", head->mybuff);
head = head->next;
}
}
void destroylist (struct list ** tail) {
if (NULL == tail) return;
while (*tail) {
struct list ** next = &((*tail)->next);
(*tail)->next = NULL;
free ((*tail)->mybuff);
free (*tail);
tail = next;
}
}
int main () {
int i;
char buff[51];
struct list * top = NULL, * cur, ** tailptr;
for (tailptr = &top, i=0; i < 10; i++) {
getline (buff, 50);
tailptr = add_item (tailptr, buff);
}
printlist (top);
destroylist (&top);
return 0;
}
---
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
.
- Follow-Ups:
- Re: Problem with a linked list
- From: CBFalconer
- Re: Problem with a linked list
- From: Keith Thompson
- Re: Problem with a linked list
- References:
- Problem with a linked list
- From: Xarky
- Problem with a linked list
- Prev by Date: Re: Problem with a linked list
- Next by Date: Re: Problem with a linked list
- Previous by thread: Re: Problem with a linked list
- Next by thread: Re: Problem with a linked list
- Index(es):
Relevant Pages
|