Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Linked list of integers demonstrating add node, delete node, print list, delete list
- */
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct client_t {
- int id;
- struct client_t *next;
- } client_t;
- /** add node to list */
- client_t *addClient (client_t **p, int n)
- {
- client_t *node = malloc (sizeof *node); /* allocate node */
- if (!node) { /* validate allocation */
- perror ("malloc-node");
- return NULL;
- }
- node->id = n; /* initialize members values */
- node->next = NULL;
- if (!*p) /* if 1st node, node is head */
- *p = node;
- else { /* otherwise */
- client_t *iter = *p; /* pointer to iterate */
- while (iter->next) /* iterate to end (or use a tail ptr) */
- iter = iter->next;
- iter->next = node; /* add at end */
- }
- return node; /* return new node */
- }
- /** delete node with value n from list (for loop) */
- void deleteClient (client_t **p, int n)
- {
- client_t **ppn = p; /* pointer to pointer to node*/
- client_t *pn = *p; /* pointer to node */
- for (; pn; ppn = &pn->next, pn = pn->next) {
- if (pn->id == n) {
- *ppn = pn->next; /* set address to next */
- free (pn);
- break;
- }
- }
- }
- /** delete all nodes in list */
- void deleteList (client_t *l)
- {
- client_t *iter = l;
- while (iter) {
- client_t *victim = iter;
- iter = iter->next;
- free (victim);
- }
- }
- /** print all nodes in list */
- void prn (client_t *l)
- {
- if (!l) {
- puts ("list-empty");
- return;
- }
- for (client_t *n = l; n; n = n->next)
- printf (" %d", n->id);
- putchar ('\n');
- }
- int main (void) {
- client_t *list = NULL; /* pointer to list initialized NULL */
- for (int i = 1; i < 11; i++) /* add nodes clients ids 1 - 10 */
- if (!addClient (&list, i))
- return 1;
- fputs ("original ids : ", stdout); /* output original list */
- prn (list);
- for (int i = 1; i < 11; i+=2) /* delete odd client ids 1,3,5,7,9 */
- deleteClient (&list, i);
- fputs ("deleted odd ids: ", stdout); /* output modified list */
- prn (list);
- deleteList (list); /* free all remaining nodes */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement