Advertisement
cd62131

circular list

Dec 3rd, 2018
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct Node Node;
  4. struct Node { int value; Node *next; };
  5. static Node *newNode(int);
  6. static void initCList(Node *);
  7. static void addCList(Node *, int);
  8. static void clearCList(Node *);
  9. static void showCList(Node *);
  10. static Node *newNode(int value) {
  11.     Node *new = calloc(sizeof *new, 1);
  12.     new->value = value;
  13.     new->next = NULL;
  14.     return new;
  15. }
  16. static void initCList(Node *head) {
  17.     clearCList(head);
  18. }
  19. static void addCList(Node *head, int value) {
  20.     Node *tail = head;
  21.     for (; tail->next != head; tail = tail->next) {
  22.         ;
  23.     }
  24.     Node *add = newNode(value);
  25.     tail->next = add;
  26.     add->next = head;
  27. }
  28. static void clearCList(Node *head) {
  29.     for (Node *p = head->next, *next = p->next; p != head; p = next, next = next->next) {
  30.         free(p);
  31.         head->next = next;
  32.     }
  33. }
  34. static void showCList(Node *head) {
  35.     printf("[");
  36.     for (Node *p = head->next; p != head; p = p->next) {
  37.         printf("%s%d", ((p == head->next) ? "" : ", "), p->value);
  38.     }
  39.     puts("]");
  40. }
  41. int main(void) {
  42.     Node head = { .value = 20181203, .next = &head };
  43.     initCList(&head); showCList(&head);
  44.     for (int i = 0; i < 5; ++i) {
  45.         addCList(&head, i); showCList(&head);
  46.     }
  47.     int n;
  48.     while (scanf("%d", &n) == 1) {
  49.         addCList(&head, n); showCList(&head);
  50.     }
  51.     clearCList(&head); showCList(&head);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement