Dimaland

Stack

Dec 5th, 2023
1,034
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <Windows.h>
  4.  
  5. // Структура узла стека
  6. struct Node {
  7.     int data;
  8.     struct Node* next;
  9. };
  10.  
  11. // Функция для создания нового узла
  12. struct Node* newNode(int data) {
  13.     struct Node* node = (struct Node*)malloc(sizeof(struct Node));
  14.     node->data = data;
  15.     node->next = NULL;
  16.     return node;
  17. }
  18.  
  19. // Функция для добавления элемента в стек
  20. void push(struct Node** root, int data) {
  21.     struct Node* node = newNode(data);
  22.     node->next = *root;
  23.     *root = node;
  24.     printf("%d добавлено в стек.\n", data);
  25. }
  26.  
  27. // Функция для удаления всех четных чисел из стека
  28. void removeEvenNumbers(struct Node** root) {
  29.     struct Node* current = *root;
  30.     struct Node* prev = NULL;
  31.  
  32.     while (current != NULL) {
  33.         if (current->data % 2 == 0) {
  34.             if (prev == NULL) {
  35.                 *root = current->next;
  36.                 free(current);
  37.                 current = *root;
  38.             } else {
  39.                 prev->next = current->next;
  40.                 free(current);
  41.                 current = prev->next;
  42.             }
  43.         } else {
  44.             prev = current;
  45.             current = current->next;
  46.         }
  47.     }
  48. }
  49.  
  50. // Функция для вывода содержимого стека
  51. void printStack(struct Node* root) {
  52.     if (root == NULL) {
  53.         printf("Стек пуст.\n");
  54.         return;
  55.     }
  56.     printf("Содержимое стека: ");
  57.     while (root != NULL) {
  58.         printf("%d ", root->data);
  59.         root = root->next;
  60.     }
  61.     printf("\n");
  62. }
  63.  
  64. int main() {
  65.     SetConsoleOutputCP(CP_UTF8);
  66.  
  67.     struct Node* stack = NULL;
  68.  
  69.     push(&stack, 1);
  70.     push(&stack, 2);
  71.     push(&stack, 3);
  72.     push(&stack, 4);
  73.     push(&stack, 5);
  74.  
  75.     printf("Исходное ");
  76.     printStack(stack);
  77.  
  78.     removeEvenNumbers(&stack);
  79.  
  80.     printf("Стек после удаления четных чисел: ");
  81.     printStack(stack);
  82.  
  83.     return 0;
  84. }
  85.  
Advertisement
Add Comment
Please, Sign In to add comment