Bill Cunningham wrote:
>
> pete wrote:
> >
> > /* BEGIN d_append.c */
> > /*
> > ** Demonstration of use of int list functions.
> > */
> > #include <stdio.h>
> > #include <stdlib.h>
> >
> > #define NUMBERS 15,14,13,7,20,9,8,12,11,6
> >
> > #define NMEMB(A) (sizeof (A) / sizeof *(A))
> >
> > struct d_node {
> > struct d_node *next;
> > int data;
> > };
> >
> > typedef struct d_node d_type;
>
> Wow if this is simple I'd hate to see complex.
> Whew. One step at a time
> I guess.
>
> > int d_fprintf(const d_type *node, FILE *stream);
> > d_type *d_append(d_type **head, d_type *tail, int data);
>
> I've never worked with pointers to pointers.
> Except in the command line.
> What's head and tail for?
head points to the first node of the linked list.
tail points to the last node of the linked list.
>I only used next.
What can you do with a linked list,
by only using next?
I simplified it:
/* BEGIN d_start.c */
/*
** Demonstration of use of int list functions.
** d_start
** d_append_0
*/
#include <stdio.h>
#include <stdlib.h>
#define NUMBERS 15,14,13,7,20,9,8,12,11,6
#define NMEMB(A) (sizeof (A) / sizeof *(A))
struct d_node {
struct d_node *next;
int data;
};
int d_fprintf(const struct d_node *node, FILE *stream);
struct d_node *d_start(int data);
struct d_node *d_append_0(struct d_node *tail, int data);
void d_free(struct d_node *node);
int
main(void)
{
struct d_node *head;
struct d_node *tail;
int numbers[] = {NUMBERS};
int *ptr = numbers;
int *const after = numbers + NMEMB(numbers);
puts("/* BEGIN d_start.c output */");
puts("\nOriginal order of list of ints:");
head = tail = d_start(*ptr);
if (head != NULL) {
while (++ptr != after) {
tail = d_append_0(tail, *ptr);
if (tail == NULL) {
puts("malloc trouble!");
break;
}
}
} else {
puts("malloc trouble!");
}
d_fprintf(head, stdout);
d_free(head);
puts("\n/* END d_start.c output */");
return 0;
}
int
d_fprintf(const struct d_node *node, FILE *stream)
{
int rc = 0;
while (node != NULL) {
if (0 > (rc = fprintf(stream, "%d\n", node -> data))) {
break;
}
node = node -> next;
}
return rc;
}
struct d_node *
d_start(int data)
{
struct d_node *node;
node = malloc(sizeof *node);
if (node != NULL) {
node -> next = NULL;
node -> data = data;
}
return node;
}
struct d_node *
d_append_0(struct d_node *tail, int data)
{
struct d_node *node;
node = malloc(sizeof *node);
if (node != NULL) {
node -> next = NULL;
node -> data = data;
tail -> next = node;
}
return node;
}
void
d_free(struct d_node *node)
{
struct d_node *next_node;
while (node != NULL) {
next_node = node -> next;
free(node);
node = next_node;
}
}
/* END d_start.c */
--
pete