首页 > 解决方案 > 设计具有分配功能的堆栈结构

问题描述

我正在尝试在 C 中实现堆栈。

我要做什么:

  1. 为实现设计一个带有pushpop功能的Stack结构。

  2. 创建一个Memory结构,拥有block 的 numberblock sizestack属性。 Stack属性表示内存块。块数属性表示堆栈的长度。块大小表示堆栈中每个元素可以得到的最大值。

  3. 编写一个带有大小参数的分配函数。如果给定的大小大于Memory的块大小,则分配将分配到堆栈属性中的不同块。

例如,调用allocate(27)将堆栈更新为:

allocate(27) = [10, 10, 7, 0, 0]

对于块数= 5,块大小= 10 的内存。剩余的没有最大值的元素可以被密封,直到元素被刷新。因此,下一次分配可以从上面给出的 7 之后的下一个元素位置开始。

  1. 编写一个释放函数来刷新最后使用的块。

我的工作:

首先,创建结构:

#include <stdio.h>
#include <stdlib.h> // Provides function For memory locating. allocate & deallocate.
 
struct Stack {
    int top;
};

struct Memory{
    int stack;
    int number_of_block; // 5
    int block_size; // 10
};

然后我尝试创建分配和推送功能,但它们不起作用。

int main(){
    allocate(30);
    return 0;
}

int allocate(int size){

    struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
    struct Memory* memory = (struct Memory*)malloc(sizeof(struct Memory));
    memory->block_size = 10;
    stack->top = -1;
    memory->stack = (int*)malloc(memory->block_size * sizeof(int));

    struct Memory memory = {1, 5, 10};

    for(int i = 0; i < 5; i++){
        if(size > 10){
            size = size - 10; //27 - 10 = 17 -> 17 - 10 = 7
            push(stack, 10);
        }
    }
    if(size % 10 != 0){
        int size_mod = size % 10; //27 % 10 = 7
        push(stack, size_mod);
    }
}


void push(struct Stack* stack, struct Memory* memory, int item){
    if(stack->top == memory->block_size - 1){
        return;
    }
    memory->stack[++stack->top] = item;
    printf("%d ", item);
}

标签: c

解决方案


Memory结构包含指向第一个块的指针,以及块的数量和每个块的最大大小。然后每个块包含数据和指向下一个块的指针,这意味着所有块都存储在链表中

该函数allocate返回一个指向创建的内存结构的指针。

#include <stdio.h>
#include <stdlib.h>

struct Block {
    int data;
    struct Block *next;
};

struct Memory {
    int block_count;
    int block_size;
    struct Block *head;
};

/* Push a new block onto the stack */
void push(struct Block **head, int data)
{
    struct Block *new = malloc(sizeof *new);
    if (!new) {
        printf("Error: memory allocation failed");
        exit(EXIT_FAILURE);
    }
    new->data = data;
    *head = new;
    /* `printf` is not needed */
    printf("%d\n", data);
}

/* Returns a pointer to the `Memory` structure */
struct Memory *allocate(int size)
{
    struct Memory *memory = malloc(sizeof *memory);
    if (!memory) {
        printf("Error: memory allocation failed");
        exit(EXIT_FAILURE);
    }
    memory->block_count = 5;
    memory->block_size = 10;

    struct Block *head = NULL;

    for (int i = 0; i < memory->block_count; ++i) {
        int data = 0;
        if (size > 10)
            data = 10;
        else if (size > 0)
            data = size;
        size -= data;
        push(&head, data);
    }
    memory->head = head;

    return memory;
}

int main(void)
{
    struct Memory *memory = allocate(27);
    return EXIT_SUCCESS;
}

如您所见,您不需要强制转换 malloc,因为它返回void *,它会自动且安全地提升为任何其他指针。


推荐阅读