A
arnuld
First, you need to see that there are two structures. One has stuff
about the whole list (its head, its tail, its length) and the other
will have the data and the next pointers. Once you get that, I think
your question will evaporate.
Okay, I have made 2 structures but now I get a Segfault in list_add() at
this line:
(*t)->head = *s;
Here is the code:
/* This C implementation of singly linked list implements 3 operations: add, remove and print elements in the list. Its is the modified
* version of my singly linked list suggested by Ben from comp.lang.c . I was using one struct to do all the operations but Ben added
* a 2nd struct to make things easier and efficient.
*
* I was always using the strategy of searching through the list to find the end and then addd the value there. That way list_add() was
* O(n). Now I am keeping track of tail and always use tail to add to the linked list, so the addition is always O(1), only at the cost
* of one assignment.
*
*
* VERISON 0.0
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct my_struct
{
int num;
struct my_struct* next;
};
struct my_list
{
struct my_struct* head;
struct my_struct* tail;
};
struct my_struct* list_add( struct my_struct**, struct my_list**, const int);
void list_print( const struct my_struct* );
void list_print_element(const struct my_struct *const );
int main(void)
{
struct my_struct* ms = NULL;
struct my_list* mt = NULL;
list_add(&ms, &mt, 1);
return 0;
}
/* Will always return the list head */
struct my_struct* list_add(struct my_struct** s, struct my_list** t, const int i)
{
struct my_struct* p = malloc( 1 * sizeof(*p) );
if( NULL == p )
{
fprintf(stderr, "IN %s, %s: malloc() failed\n", __FILE__, "list_add");
return NULL;
}
p->num = i;
p->next = NULL;
if( NULL == *s && NULL == *t)
{
printf("Empty list, adding p->num: %d\n\n", p->num);
printf("*s = %p\n", (void*)*s);
*s = p;
printf("*s = %p\n", (void*)*s);
printf("*t = %p\n", (void*)*t);
(*t)->head = *s;
printf("my_list head is assigned\n");
(*t)->tail = *s;
printf("my_list tail is assigned\n");
return (*t)->head;
}
else if( NULL == *s || NULL == *t )
{
printf("Something is seriously wrong with the assignment of head and tail\n");
return NULL;
}
else
{
(*t)->tail->next = p;
return (*t)->head;
}
}
void list_print( const struct my_struct *const sp )
{
const struct my_struct* p = sp;
for( ; NULL != p; p = p->next )
{
list_print_element(p);
}
printf("\n------------------\n");
}
void list_print_element(const struct my_struct *const p )
{
if( p )
{
printf("Num = %d\n", p->num);
}
else
{
printf("Can not print NULL struct \n");
}
}