Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!border3.nntp.dca.giganews.com!Xl.tags.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local2.nntp.dca.giganews.com!nntp.earthlink.com!news.earthlink.com.POSTED!not-for-mail NNTP-Posting-Date: Thu, 06 Sep 2012 17:22:25 -0500 Message-ID: <50492222.5F6D@mindspring.com> Date: Thu, 06 Sep 2012 18:22:26 -0400 From: pete Reply-To: pfiland@mindspring.com Organization: PF X-Mailer: Mozilla 3.04Gold (WinNT; I) MIME-Version: 1.0 Newsgroups: comp.programming Subject: Re: linked list References: Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Lines: 103 X-Usenet-Provider: http://www.giganews.com NNTP-Posting-Host: 4.156.228.243 X-Trace: sv3-X5WXc5n7N39dSp2wPPgfSnYsXAdnIs3rMYH1p9GxMHERxVEqslMuk7hfzs4AsBRHTUlMXyEobqF8YHd!mwmB6HgnkmW9w0W1rh0BbMK4qaS1+y5trucaNrQkcFHQ76xXd0eTkh//sLi1UCcn4BTD/8Y8tM2U!vcYKqqm7bLU= X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 X-Original-Bytes: 3036 Xref: csiph.com comp.programming:2174 Bill Cunningham wrote: > > Can someone show me a very simple example > of a linked list in C? The simplest possible. /* BEGIN d_append.c */ /* ** Demonstration of use of int list functions. */ #include #include #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; int d_fprintf(const d_type *node, FILE *stream); d_type *d_append(d_type **head, d_type *tail, int data); void d_free(d_type *node); int main(void) { d_type *head = NULL; d_type *tail = NULL; int numbers[] = {NUMBERS}; int *ptr = numbers; int *const after = numbers + NMEMB(numbers); puts("/* BEGIN d_append.c output */"); puts("\nOriginal order of list of ints:"); do { tail = d_append(&head, tail, *ptr); if (tail == NULL) { puts("malloc trouble!"); break; } } while (++ptr != after); d_fprintf(head, stdout); d_free(head); puts("\n/* END d_append.c output */"); return 0; } int d_fprintf(const d_type *node, FILE *stream) { int rc = 0; while (node != NULL) { if (0 > (rc = fprintf(stream, "%d\n", node -> data))) { break; } node = node -> next; } return rc; } d_type * d_append(d_type **head, d_type *tail, int data) { d_type *node; node = malloc(sizeof *node); if (node != NULL) { node -> next = NULL; node -> data = data; if (*head != NULL) { tail -> next = node; } else { *head = node; } } return node; } void d_free(d_type *node) { d_type *next_node; while (node != NULL) { next_node = node -> next; free(node); node = next_node; } } /* END d_append.c */ -- pete