diff --git a/src/python/dfs.py b/src/dfs/main.py similarity index 85% rename from src/python/dfs.py rename to src/dfs/main.py index 462fff2..a42cc67 100644 --- a/src/python/dfs.py +++ b/src/dfs/main.py @@ -32,12 +32,3 @@ def dfs(self, start): def __iter__(self): start = list(self.adj_list.keys())[0] return iter(self.dfs(start)) -#пример -g = Graph() -g.add_edge('A', 'B') -g.add_edge('A', 'C') -g.add_edge('B', 'D') - -print("Обход DFS:", g.dfs('A')) # ['A', 'C', 'B', 'D'] - - diff --git a/src/dfs/tests.py b/src/dfs/tests.py new file mode 100644 index 0000000..f11a6aa --- /dev/null +++ b/src/dfs/tests.py @@ -0,0 +1,54 @@ +import pytest +from main import Graph + +def test_simple_graph(): + g = Graph() + g.add_edge('A', 'B') + g.add_edge('A', 'C') + g.add_edge('B', 'D') + + result = g.dfs('A') + + assert set(result) == {'A', 'B', 'C', 'D'} + assert result[0] == 'A' + assert 'A' == result[0] + assert 'C' in result[1:] + assert 'B' in result[1:] + assert result.index('D') > result.index('B') + +def test_graph_with_disconnected_components(): + g = Graph() + g.add_edge('A', 'B') + g.add_edge('C', 'D') + + result = g.dfs('A') + assert 'A' in result + assert 'B' in result + assert 'C' not in result + assert 'D' not in result + +def test_iteration_over_graph(): + g = Graph() + g.add_edge('A', 'B') + g.add_edge('A', 'C') + g.add_edge('B', 'D') + nodes_in_iteration = list(iter(g)) + + assert set(nodes_in_iteration) == {'A', 'B', 'C', 'D'} + assert nodes_in_iteration[0] == list(g.adj_list.keys())[0] + +def test_cycle_graph(): + g = Graph() + g.add_edge('A', 'B') + g.add_edge('B', 'C') + g.add_edge('C', 'A') + + result = g.dfs('A') + assert set(result) == {'A', 'B', 'C'} + assert result[0] == 'A' + +def test_single_vertex(): + g = Graph() + g.add_vertex('X') + result = g.dfs('X') + assert result == ['X'] diff --git a/src/python/Fibonacci of a large number.png b/src/python/Fibonacci of a large number.png deleted file mode 100644 index a91f41f..0000000 Binary files a/src/python/Fibonacci of a large number.png and /dev/null differ diff --git a/src/python/Heap_sort.py b/src/python/Heap_sort.py deleted file mode 100644 index 15dad65..0000000 --- a/src/python/Heap_sort.py +++ /dev/null @@ -1,76 +0,0 @@ -import pytest -import random - -def heapify(nums, heap_size, root_index): - largest = root_index - l_child = (2 * root_index) + 1 - r_child = (2 * root_index) + 2 - - if l_child < heap_size and nums[l_child] > nums[largest]: - largest = l_child - - if r_child < heap_size and nums[r_child] > nums[largest]: - largest = r_child - - if largest != root_index: - nums[root_index], nums[largest] = nums[largest], nums[root_index] - heapify(nums, heap_size, largest) - -def heap_sort(nums): - n = len(nums) - - for i in range(n, -1, -1): - heapify(nums, n, i) - - for i in range(n - 1, 0, -1): - nums[i], nums[0] = nums[0], nums[i] - heapify(nums, i, 0) - -def test_empty(): - arr = [] - heap_sort(arr) - assert arr == [] - -def test_single_element(): - arr = [42] - heap_sort(arr) - assert arr == [42] - -def test_sorted_array(): - arr = [1, 2, 3, 4, 5] - heap_sort(arr) - assert arr == sorted(arr) - -def test_reverse_sorted_array(): - arr = [5, 4, 3, 2, 1] - heap_sort(arr) - assert arr == sorted(arr) - -def test_duplicates(): - arr = [2, 3, 2, 1, 3, 1] - heap_sort(arr) - assert arr == sorted(arr) - -def test_all_equal(): - arr = [7, 7, 7, 7] - heap_sort(arr) - assert arr == [7, 7, 7, 7] - -def test_negative_numbers(): - arr = [-3, -1, -7, 4, 0] - heap_sort(arr) - assert arr == sorted(arr) - -def test_large_array(): - arr = list(range(1000, 0, -1)) - expected = list(range(1, 1001)) - heap_sort(arr) - assert arr == expected - -def test_random_arrays(): - for _ in range(10): - size = random.randint(0, 1000) - arr = [random.randint(-10000, 10000) for _ in range(size)] - arr_copy = arr[:] - heap_sort(arr) - assert arr == sorted(arr_copy) diff --git a/src/python/Hello World.py b/src/python/Hello World.py deleted file mode 100644 index 70d26e8..0000000 --- a/src/python/Hello World.py +++ /dev/null @@ -1,12 +0,0 @@ - CALL 1 - LOAD_FAST 0 (n) - COMPARE_OP 88 (bool(==)) - POP_JUMP_IF_FALSE 5 (to L1) - - LOAD_FAST 0 (n) - LOAD_CONST 2 (3) - BINARY_OP 8 (**) - RETURN_VALUE - - L1: RETURN_CONST 0 (None) - L2: RETURN_CONST 0 (None) diff --git a/src/python/carrying.py b/src/python/carrying.py deleted file mode 100644 index 4fd009c..0000000 --- a/src/python/carrying.py +++ /dev/null @@ -1,48 +0,0 @@ -def curry(func, n): - if not isinstance(n, int): - raise TypeError("Error! type(n)!=int") - if n < 0: - raise ValueError("Error! n<0") - if n == 0: - return func - - def start(initial_arg): - collected_args = [initial_arg] - if n == 1: - return func(initial_arg) - - def cont(next_arg): - collected_args.append(next_arg) - if len(collected_args) == n: - return func(*collected_args) - return cont - - return cont - return start - - -def uncurry(curry_func, n): - if not isinstance(n, int): - raise TypeError("Error! type(n)!=int") - if n < 0: - raise ValueError("Error! n<0") - if n == 0: - return curry_func - - def uncurried(*args): - if len(args) != n: - raise ValueError(f"Error! You give a count of arguments != n") - res = curry_func - for a in args: - res = res(a) - return res - - return uncurried - -def sum3(x, y, z): - return x + y + z - -sum3_curry = curry(sum3, 3) -sum3_uncurry = uncurry(sum3_curry, 3) -print(sum3_curry(1)(2)(3)) # 6 -print(sum3_uncurry(1, 2, 3)) # 6 diff --git a/src/python/coin_exchange.py b/src/python/coin_exchange.py deleted file mode 100644 index 6ef9f3e..0000000 --- a/src/python/coin_exchange.py +++ /dev/null @@ -1,13 +0,0 @@ -num = int(input('Enter the number: ')) - -nominal_1 = len('Pentegova') -nominal_2 = len('Maria') -nominal_3 = len('Sergeevna') - -for i_1 in range(num // nominal_1 + 1): - for i_2 in range(num // nominal_2 + 1): - for i_3 in range(num // nominal_3 + 1): - if i_1 * nominal_1 + i_2 * nominal_2 + i_3 * nominal_3 == num: - print(i_1,'*',nominal_1,'+',i_2,'*',nominal_2,'+',i_3,'*',nominal_3) - exit() -print("-42!") diff --git a/src/python/do_eratosthenes.py b/src/python/do_eratosthenes.py deleted file mode 100644 index 4392706..0000000 --- a/src/python/do_eratosthenes.py +++ /dev/null @@ -1,16 +0,0 @@ -def do_eratosthenes(n): - numbers = [True] * (n + 1) #все числа изначально простые - numbers[0] = False - numbers[1] = False - - for i in range(2, n + 1): - if numbers[i]==True: - for j in range(i*i, n + 1, i): - numbers[j] = False - - for i in range(2, n + 1): - if numbers[i]: - print(i, end=' ') - -num = int(input("Enter the number: ")) -do_eratosthenes(num) diff --git a/src/python/extended_euclud.py b/src/python/extended_euclud.py deleted file mode 100644 index 0f1ed3e..0000000 --- a/src/python/extended_euclud.py +++ /dev/null @@ -1,17 +0,0 @@ -def extended_euclid(a, b): - if b == 0: - return a, 1, 0 - else: - gcd, x1, y1 = extended_euclid(b, a % b) - - x = y1 - y = x1 - (a // b) * y1 - return gcd, x, y - -a = int(input("Enter a: ")) -b = int(input("Enter b: ")) - -gcd, x, y = extended_euclid(a, b) - -print(f"gcd({a}, {b}) = {gcd}") -print(f"{a}*({x}) + {b}*({y}) = {a*x + b*y}") diff --git a/src/python/haffman_code.py b/src/python/haffman_code.py deleted file mode 100644 index 21ca262..0000000 --- a/src/python/haffman_code.py +++ /dev/null @@ -1,84 +0,0 @@ -import heapq -import pickle - -def build_huffman_tree(text: str): - freq = {} - for ch in text: - freq[ch] = freq.get(ch, 0) + 1 - heap = [[weight, [char, '']] for char, weight in freq.items()] - heapq.heapify(heap) - while len(heap) > 1: - lo = heapq.heappop(heap) - hi = heapq.heappop(heap) - for pair in lo[1:]: - pair[1] = '0' + pair[1] - for pair in hi[1:]: - pair[1] = '1' + pair[1] - heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) - if heap: - return dict(sorted(heap[0][1:], key=lambda p: p[0])) - else: - return {} - -def generate_table(message: str) -> dict: - return build_huffman_tree(message) - -def encode(message: str) -> tuple[str, dict]: - table = generate_table(message) - encoded_message = ''.join([table[ch] for ch in message]) - return encoded_message, table - -def decode(encoded_str: str, table: dict) -> str: - reversed_table = {v: k for k, v in table.items()} - current_code = '' - decoded_message = '' - for bit in encoded_str: - current_code += bit - if current_code in reversed_table: - decoded_message += reversed_table[current_code] - current_code = '' - return decoded_message - -def save_to_file(filepath: str, message: str): - encoded_str, table = encode(message) - - # сериализация таблицы - table_bytes = pickle.dumps(table) - table_size = len(table_bytes) - - # padding for byte alignment - padding_size = (8 - len(encoded_str) % 8) % 8 - encoded_str_padded = encoded_str + '0' * padding_size - - # строка в байты - byte_array = bytearray() - for i in range(0, len(encoded_str_padded), 8): - byte = encoded_str_padded[i:i+8] - byte_array.append(int(byte, 2)) - - with open(filepath, 'wb') as f: - f.write(table_size.to_bytes(4, byteorder='big')) - f.write(table_bytes) - f.write(padding_size.to_bytes(1, byteorder='big')) - f.write(byte_array) - -def load_from_file(filepath: str) -> str: - with open(filepath, 'rb') as f: - table_size_bytes = f.read(4) - table_size = int.from_bytes(table_size_bytes, byteorder='big') - table_bytes = f.read(table_size) - table = pickle.loads(table_bytes) - padding_size = int.from_bytes(f.read(1), byteorder='big') - message_bytes = f.read() - bits_str = ''.join([format(byte, '08b') for byte in message_bytes]) - if padding_size > 0: - bits_str = bits_str[:-padding_size] - return decode(bits_str, table) - -# Пример использования: -# сохранить в файл -# save_to_file('huffman.bin', 'Ваш текст для сжатия') - -# загрузить и расшифровать -# original_text = load_from_file('huffman.bin') -# print(original_text) diff --git a/src/works_on_C/Lucky tickets.c b/src/works_on_C/Lucky tickets.c deleted file mode 100644 index 2abed99..0000000 --- a/src/works_on_C/Lucky tickets.c +++ /dev/null @@ -1,28 +0,0 @@ -#include - -int countTriplesForSum(int s) { - int count = 0; - for (int a = 0; a <= 9; ++a) { - for (int b = 0; b <= 9; ++b) { - for (int c = 0; c <= 9; ++c) { - if (a + b + c == s) - ++count; - } - } - } - return count; -} - -int getLuckyTicketsAmount() { - int total = 0; - for (int s = 0; s <= 27; ++s) { - int count = countTriplesForSum(s); - total += count * count; - } - return total; -} - -int main() { - printf("%d\n", getLuckyTicketsAmount()); - return 0; -} diff --git a/src/works_on_C/array_flip.c b/src/works_on_C/array_flip.c deleted file mode 100644 index 914f99e..0000000 --- a/src/works_on_C/array_flip.c +++ /dev/null @@ -1,32 +0,0 @@ -#include - -void do_reverse(int *arr, int start, int end) { - while (start < end) { - int t = arr[start]; - arr[start] = arr[end]; - arr[end] = t; - start++; - end--; - } -} - -void swap_segments(int *arr, int len, int m) { - do_reverse(arr, 0, m - 1); - do_reverse(arr, m, len - 1); - do_reverse(arr, 0, len - 1); -} - -int main() { - int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; - int m = 3; - int n = 5; - int len = m + n; - - swap_segments(arr, len, m); - - for (int i = 0; i < len; i++) { - printf("%d ", arr[i]); - } - printf("\n"); - return 0; -} diff --git a/src/works_on_C/check_string.c b/src/works_on_C/check_string.c deleted file mode 100644 index 0ba292a..0000000 --- a/src/works_on_C/check_string.c +++ /dev/null @@ -1,32 +0,0 @@ -#include - -int check_string(char *string, char l_bracket) { - char r_bracket; - if (l_bracket == '(') - r_bracket = ')'; - else if (l_bracket == '[') - r_bracket = ']'; - else if (l_bracket == '{') - r_bracket = '}'; - else - return 0; - - int c = 0; - for (int i = 0; string[i] != '\0'; i++) { - if (string[i] == l_bracket) - c++; - else if (string[i] == r_bracket) { - if (c == 0) - return 0; - c--; - } - } - return c == 0; -} - -int main() { - printf("%d\n", check_string("при((ве)т)", '(')); - printf("%d\n", check_string("пр[ив[ет]]", '[')); - printf("%d\n", check_string("пр}ив{е}{т", '{')); - return 0; -} diff --git a/src/works_on_C/count_zero.c b/src/works_on_C/count_zero.c deleted file mode 100644 index e7caa16..0000000 --- a/src/works_on_C/count_zero.c +++ /dev/null @@ -1,17 +0,0 @@ -#include - -int count_zero(int *arr, int len){ - int c = 0; - for (int i=0; i - -int find_quotient(int a, int b){ - int r = a; - if (b == 0) - r = -1; // Деление на ноль - - int b_abs = (b < 0) ? -b : b; - - if (a >= 0) { - while (r >= b_abs) { - r -= b_abs; - } - } - - else { - while (r < 0) { - r += b_abs; - } - } - - return r; -} - -int main(){ - printf("%d\n", find_quotient(7, 4)); // 7=4*1+3 - printf("%d\n", find_quotient(7, -4)); // 7=-4*(-1)+3 - printf("%d\n", find_quotient(-7, 4)); // -7=4*(-2)+1 - printf("%d\n", find_quotient(-7, -4)); // -7=-4*2+1 - printf("%d\n", find_quotient(7, 0)); // -1, делить на 0 нельзя - printf("%d\n", find_quotient(0, 4)); // 0=4*0+0 -} diff --git a/src/works_on_C/more_difficult/advanced_bracket-2.c b/src/works_on_C/more_difficult/advanced_bracket-2.c deleted file mode 100644 index 80f1e06..0000000 --- a/src/works_on_C/more_difficult/advanced_bracket-2.c +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define MAX_STACK_SIZE 100 - -int check_string(const char *string, char *stack, int *top) { - *top = -1; - for (int i = 0; string[i] != '\0'; i++) { - char c = string[i]; - - if (c == '(' || c == '[' || c == '{') { - if (*top >= MAX_STACK_SIZE - 1) return 0; // переполнение стека - stack[++(*top)] = c; - } else if (c == ')' || c == ']' || c == '}') { - if (*top < 0) return 0; // стек пуст, неправильная последовательность - char open = stack[(*top)--]; - if ((open == '(' && c != ')') || - (open == '[' && c != ']') || - (open == '{' && c != '}')) - return 0; - } - } - return (*top == -1); -} - -int main() { - char stack[MAX_STACK_SIZE]; - int top; - - printf("%d\n", check_string("({)}", stack, &top)); // должно быть 0 - printf("%d\n", check_string("({})", stack, &top)); // должно быть 1 - return 0; -} diff --git a/src/works_on_C/more_difficult/binary_represent.c b/src/works_on_C/more_difficult/binary_represent.c deleted file mode 100644 index 75ef382..0000000 --- a/src/works_on_C/more_difficult/binary_represent.c +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include - -void printBinary(int num) { - for (int i = 31; i >= 0; i--) { - printf("%d", (num >> i) & 1); - if (i % 4 == 0 && i != 0) printf(" "); // для удобства - } - printf("\n"); -} - -void printComplementCode(int num) { - printBinary(num); -} - -unsigned int addBinary(int a, int b, int *carry_out) { - unsigned int result = 0; - int carry = 0; - for (int i=0; i<32; i++) { - int bitA = (a >> i) & 1; - int bitB = (b >> i) & 1; - - int sum = bitA ^ bitB ^ carry; // сложение без переноса - carry = (bitA & bitB) | (bitA & carry) | (bitB & carry); // перенос - - result |= (sum << i); - } - *carry_out = carry; - return result; -} - -int main() { - int num1, num2; - printf("Введите первое число (целое): "); - scanf("%d", &num1); - printf("Введите второе число (целое): "); - scanf("%d", &num2); - - printf("Первое число в двоичном виде: "); - printComplementCode(num1); - printf("%d/n", printBinary(num)); - printf("Второе число в двоичном виде: "); - printComplementCode(num2); - - int carry = 0; - unsigned int sum = addBinary(num1, num2, &carry); - - printf("Сумма в двоичном виде: "); - printBinary(sum); - printf("Перенос после сложения (если есть): %d\n", carry); - - printf("Сумма в десятичном виде: %d\n", (int)sum); - - return 0; -} diff --git a/src/works_on_C/more_difficult/counting_rhyme.c b/src/works_on_C/more_difficult/counting_rhyme.c deleted file mode 100644 index d19a321..0000000 --- a/src/works_on_C/more_difficult/counting_rhyme.c +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include - -typedef struct Node { - int number; - struct Node *next; -} Node; - -// циклический список из n воинов -Node* create_circle(int n) { - Node *head = NULL, *prev = NULL; - for (int i = 1; i <= n; i++) { - Node *new_node = (Node*)malloc(sizeof(Node)); - new_node->number = i; - if (head == NULL) { - head = new_node; - } else { - prev->next = new_node; - } - prev = new_node; - } - prev->next = head; - return head; -} - -Node* delete_node(Node *node, Node *prev) { - prev->next = node->next; - free(node); - return prev->next; -} - -int to_end(int n, int m) { - Node *circle = create_circle(n); - Node *current = circle; - Node *prev = NULL; - - while (prev == NULL || prev->next != current) { - prev = current; - current = current->next; - if (current == circle && prev->next != current) { - break; - } - } - - while (current->next != current) { - for (int count = 1; count < m; count++) { - prev = current; - current = current->next; - } - printf("Убит воин #%d\n", current->number); - current = delete_node(current, prev); - } - - int survivor = current->number; - free(current); - return survivor; -} - -int main() { - int n = 41; - int m; - - printf("Введите число, соответствующее убивающего каждого m-го: "); - scanf("%d", &m); - - int last = to_end(n, m); - printf("Последним остается воин #%d\n", last); - return 0; -} diff --git a/src/works_on_C/more_difficult/double.c b/src/works_on_C/more_difficult/double.c deleted file mode 100644 index 0740304..0000000 --- a/src/works_on_C/more_difficult/double.c +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include - -typedef union { - double value; - unsigned char bytes[8]; -} Number; - -int get_bit(Number num, int i) { - int byte_index = i / 8; - int bit_index = i % 8; - return (num.bytes[byte_index] >> bit_index) & 1; -} - -void to_normal(double num) { - Number number; - number.value = num; - - int sign_bit = get_bit(number, 63); - char sign_char = sign_bit ? '-' : '+'; - - int exponent_bits = 0; - for (int i = 52; i <= 62; i++) { - exponent_bits = (exponent_bits << 1) | get_bit(number, i); - } - - uint64_t mantissa_bits = 0; - for (int i = 0; i < 52; i++) { - mantissa_bits = (mantissa_bits << 1) | get_bit(number, i); - } - - int bias = 1023; - int p = exponentBits - bias; - double m; - - m = 1.0 + mantissa_bits / (double)(1ULL << 52); - - printf("Result: %c%.20f*2^%d\n", sign_char, m, p); -} - -int main() { - double x; - printf("Enter a number: "); - scanf("%lf", &x); - to_normal(x); - return 0; -} diff --git a/src/works_on_C/more_difficult/optimal_sorting/instruction.txt b/src/works_on_C/more_difficult/optimal_sorting/instruction.txt deleted file mode 100644 index 823e46a..0000000 --- a/src/works_on_C/more_difficult/optimal_sorting/instruction.txt +++ /dev/null @@ -1,2 +0,0 @@ -To build the code: -gcc -m64 -o sort_app main.c sort.s diff --git a/src/works_on_C/more_difficult/optimal_sorting/main.c b/src/works_on_C/more_difficult/optimal_sorting/main.c deleted file mode 100644 index cf723d8..0000000 --- a/src/works_on_C/more_difficult/optimal_sorting/main.c +++ /dev/null @@ -1,29 +0,0 @@ -#include - -#define MAX_SIZE 100 - -extern int sort(int *arr, int size); - -int main() { - int arr[MAX_SIZE]; - int n = 0; - int num; - - while (n < MAX_SIZE && scanf("%d", &num) == 1) { - arr[n++] ; - int c = getchar(); - if (c == '\n' || c == EOF) - break; - ungetc(c, stdin); - } - - if (n == 0) { - return 0; - } - - int changed_count = sort(arr, n); - - printf("%d\n", changed_count); - - return changed_count; -} diff --git a/src/works_on_C/more_difficult/optimal_sorting/sort.s b/src/works_on_C/more_difficult/optimal_sorting/sort.s deleted file mode 100644 index 961aaca..0000000 --- a/src/works_on_C/more_difficult/optimal_sorting/sort.s +++ /dev/null @@ -1,55 +0,0 @@ - .global sort - .type sort, @function - -sort: - push %rbp - mov %rsp, %rbp - - mov %rsi, %rcx - cmp $1, %rcx - jle end - - mov $0, %rdx - - xor %r8, %r8 -outer_loop: - cmp %r8, %rcx - jge end_outer - - xor %r9, %r9 -inner_loop: - mov %r8, %rax - inc %rax - cmp %rax, %rcx - jge end_inner - - mov %rdi, %r10 - mov %r9, %r11 - shl $2, %r11 - mov (%r10,%r11), %r12 - mov %r9, %r13 - shl $2, %r13 - lea 4(%r10,%r13), %r14 - mov (%r14), %r15 - - cmp %r15, %r12 - JGE skip_swap - mov %r15, (%r10,%r11) - mov %r12, (%r14) - - inc %rdx - -skip_swap: - inc %r9 - jmp inner_loop - -end_inner: - inc %r8 - jmp outer_loop - -end_outer: - mov %rdx, %rax - -end: - pop %rbp - ret diff --git a/src/works_on_C/more_difficult/sorting_list.c b/src/works_on_C/more_difficult/sorting_list.c deleted file mode 100644 index 0cdd679..0000000 --- a/src/works_on_C/more_difficult/sorting_list.c +++ /dev/null @@ -1,112 +0,0 @@ -#include -#include - -typedef struct Node { - int value; - struct Node* next; -} Node; - -// Функция для вставки элемента в отсортированный список -void insert_sorted(Node** head, int value) { - Node* new_node = (Node*)malloc(sizeof(Node)); - new_node->value = value; - new_node->next = NULL; - - if (*head == NULL || (*head)->value >= value) { - new_node->next = *head; - *head = new_node; - return; - } - - Node* current = *head; - while (current->next != NULL && current->next->value < value) { - current = current->next; - } - - new_node->next = current->next; - current->next = new_node; -} - -void delete_value(Node** head, int value) { - Node* current = *head; - Node* prev = NULL; - - while (current != NULL && current->value != value) { - prev = current; - current = current->next; - } - - if (current == NULL) { - printf("Значение %d не найден.\n", value); - return; - } - - if (prev == NULL) { - // Удаляем головой списка - *head = current->next; - } else { - prev->next = current->next; - } - - free(current); - printf("Значение %d удалено.\n", value); -} - -void print_list(Node* head) { - printf("Список: "); - Node* current = head; - while (current != NULL) { - printf("%d ", current->value); - current = current->next; - } - printf("\n"); -} - -void free_list(Node* head) { - Node* tmp; - while (head != NULL) { - tmp = head; - head = head->next; - free(tmp); - } -} - -int main() { - Node* head = NULL; - int choice; - int value; - - while (1) { - printf("\nМеню:\n"); - printf("0 - выйти\n"); - printf("1 - добавить значение\n"); - printf("2 - удалить значение\n"); - printf("3 - распечатать список\n"); - printf("Введите ваш выбор: "); - scanf("%d", &choice); - - switch (choice) { - case 0: - free_list(head); - printf("Выход...\n"); - return 0; - case 1: - printf("Введите значение для добавления: "); - scanf("%d", &value); - insert_sorted(&head, value); - break; - case 2: - printf("Введите значение для удаления: "); - scanf("%d", &value); - delete_value(&head, value); - break; - case 3: - print_list(head); - break; - default: - printf("Некорректный выбор.\n"); - } - } - - return 0; -} diff --git a/src/works_on_C/more_difficult/sorting_station.c b/src/works_on_C/more_difficult/sorting_station.c deleted file mode 100644 index f4c0fb5..0000000 --- a/src/works_on_C/more_difficult/sorting_station.c +++ /dev/null @@ -1,86 +0,0 @@ -#include -#include -#include - -#define MAX_LEN 100 - -int precedence(char op) { - if (op == '+' || op == '-') return 1; - if (op == '*' || op == '/') return 2; - return 0; -} - -void infix_to_postfix(const char *infix, char *postfix) { - // стек для операторов - char stack[MAX_LEN]; - int top = -1; // стек пуст - - int j = 0; // индекс для postfix - - for (int i = 0; infix[i] != '\0'; i++) { - char c = infix[i]; - - if (isspace(c)) { - continue; - } - - if (isdigit(c)) { - while (isdigit(infix[i])) { - postfix[j++] = infix[i++]; - } - postfix[j++] = ' '; - i--; - } else if (c == '(') { - if (top < MAX_LEN - 1) { - stack[++top] = c; - } - } else if (c == ')') { - while (top >= 0 && stack[top] != '(') { - postfix[j++] = stack[top--]; - postfix[j++] = ' '; - } - if (top >= 0 && stack[top] == '(') { - top--; - } - } else if (is_operator(c)) { - while (top >= 0 && is_operator(stack[top]) && precedence(stack[top]) >= precedence(c)) { - postfix[j++] = stack[top--]; - postfix[j++] = ' '; - } - if (top < MAX_LEN - 1) { - stack[++top] = c; - } - } - } - - while (top >= 0) { - if (stack[top] == '(') { - top--; - } else { - postfix[j++] = stack[top--]; - postfix[j++] = ' '; - } - } - - postfix[j] = '\0'; -} - -int is_operator(char c) { - return c == '+' || c == '-' || c == '*' || c == '/'; -} - -int main() { - char infix[MAX_LEN]; - char postfix[MAX_LEN * 2]; // резерв для разделителей и чисел - - printf("Enter: "); - fgets(infix, MAX_LEN, stdin); - size_t len = strlen(infix); - if (len > 0 && infix[len - 1] == '\n') { - infix[len - 1] = '\0'; - } - - infix_to_postfix(infix, postfix); - printf("Postfix form: %s\n", postfix); - return 0; -}