Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Задача 1.1. Число делится на NUM, остаток записывается в стек. Затем стек выводится.
- * Ограничение программы - до UINT_MAX (2^32)
- *
- * Она же - Задача 1.2. Пашет, так как при неявном приведении типов выполняется перевод в двоичный код
- * Ограничение - до -2^31
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <limits.h>
- #define NUM 2
- /* Реализация стека */
- typedef struct _stack
- {
- unsigned value;
- struct _stack *next;
- } stack;
- stack* new_stack () //Конструктор стека
- {
- stack* head = (stack*)malloc(sizeof(stack));
- head->next = NULL;
- return head;
- }
- void push (stack **head, unsigned data) //Добавление элемента a в стек
- {
- stack* elem = (stack*)malloc(sizeof(stack)); //Создали элемент
- elem->value = data;
- elem->next = (*head); //Связываем со стеком
- (*head) = elem;
- }
- unsigned pop(stack **head)
- { //Получение первого элемента и удаление его из стека
- stack* prev = NULL;
- unsigned val;
- if ((*head)->next == NULL)
- {
- fprintf(stderr, "Attempt to extract an element from an empty stack\n");
- exit(-1);
- }
- prev = (*head);
- val = prev->value;
- (*head) = (*head)->next;
- free(prev);
- return val;
- }
- void print(const stack* head)
- { //Печать стека
- while (head->next != NULL)
- {
- printf("%d \n", head->value);
- head = head->next;
- }
- }
- void stack_delete (stack **head) //Деструктор стека
- {
- while ((*head)->next)
- {
- pop(head);
- *head = (*head)->next;
- }
- free(*head);
- }
- int isEmpty (stack* head) //Проверка на пустоту
- {
- if (head->next == NULL)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- int main ()
- {
- printf("%u\n", UINT_MAX);
- unsigned a = 0;
- stack* s = new_stack();
- scanf("%u", &a);
- printf("%u\n", a);
- if (!a)
- {
- printf("0");
- return 0;
- }
- while (a)
- {
- push(&s, a % NUM);
- a /= NUM;
- }
- while (!isEmpty(s))
- {
- printf("%u", pop(&s));
- }
- stack_delete(&s);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement