Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct _Node
  5. {
  6.   int value;
  7.   struct _Node *next;
  8. } Node;
  9.  
  10. Node *createNode(int value)
  11. {
  12.   Node *newNode = (Node *)malloc(sizeof(Node));
  13.   newNode->value = value;
  14.   newNode->next = NULL;
  15.   return newNode;
  16. }
  17.  
  18. void pushFront(Node **list, int value)
  19. {
  20.   Node *nextElem = createNode(value);
  21.   nextElem->next = (*list);
  22.   (*list) = nextElem;
  23. }
  24.  
  25. Node *getTail(Node *list)
  26. {
  27.   if (list == NULL)
  28.     return NULL;
  29.   while (list->next)
  30.     list = list->next;
  31.   return list;
  32. }
  33.  
  34. Node* getPenultimate(Node* list)
  35. {
  36.     while(list->next->next)
  37.         list=list->next;
  38.     return list;
  39. }
  40.  
  41. void pushBack(Node **list, int value)
  42. {
  43.   Node *tail = getTail((*list));
  44.   Node *elem = createNode(value);
  45.   elem->next = NULL;
  46.   tail->next = elem;
  47. }
  48.  
  49. void popFront(Node **list)
  50. {
  51.   if ((*list) == NULL)
  52.     return;
  53.   Node *next = (*list)->next;
  54.   free((*list));
  55.   (*list) = next;
  56. }
  57.  
  58. void popBack(Node **list)
  59. {
  60.   if ((*list) == NULL)
  61.     return;
  62.   Node* tail = getPenultimate((*list));
  63.   free(tail->next);
  64.   tail->next = NULL;
  65. }
  66.  
  67. int main()
  68. {
  69.   Node *n = createNode(12);
  70.   printf("front value after createNode(12): %d \n", n->value);
  71.   pushFront(&n, 32);
  72.   printf("tail value after  pushFront(&n, 32): %d \n", getTail(n)->value);
  73.   pushBack(&n, 64);
  74.   printf("tail value after pushBack(&n, 64): %d \n", getTail(n)->value);
  75.   printf("front value after pushBack(&n, 64): %d \n", n->value);
  76.   popBack(&n);
  77.   printf("tail value after popBack(&n): %d \n", getTail(n)->value);
  78.   popFront(&n);
  79.   printf("front value after popFront(&n): %d \n", n->value);
  80.   return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement