Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <malloc.h>
  4.  
  5. typedef struct ListElement {
  6.     int value;
  7.     struct ListElement* next;
  8. } ListElement;
  9.  
  10. void Push(ListElement** head, int value) {
  11.     if (!head)
  12.         exit(-1);
  13.     ListElement* t = (ListElement*)malloc(sizeof(ListElement));
  14.     t->value = value;
  15.     t->next = (*head);
  16.     (*head) = t;
  17. }
  18.  
  19. int Pop(ListElement** head) {
  20.     ListElement* t = NULL;
  21.     int value;
  22.     if (!head)
  23.         exit(-1);
  24.     t = *head;
  25.     value = t->value;
  26.     (*head) = (*head)->next;
  27.     free(t);
  28.     return value;
  29. }
  30.  
  31. void PrintList(ListElement* head) {
  32.     while (head) {
  33.         printf("%4d", head->value);
  34.         head = head->next;
  35.     }
  36.     printf("\n");
  37. }
  38.  
  39. void DestroyList(ListElement** head) {
  40.     if (!head)
  41.         exit(-1);
  42.     if (!(*head))
  43.         exit(-1);
  44.     ListElement* tmp = NULL;
  45.     while ((*head)->next) {
  46.         tmp = (*head);
  47.         (*head) = (*head)->next;
  48.         free(tmp);
  49.     }
  50.     free(*head);
  51. }
  52.  
  53. int main() {
  54.     ListElement* head = NULL;
  55.     int n;
  56.     scanf("%d", &n);
  57.     for (int i = 0; i < n; i++)
  58.     {
  59.         Push(&head, i + 1);
  60.     }
  61.  
  62.     PrintList(head);
  63.     DestroyList(&head);
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement