简易内存池(100%用例)C卷(Java&&Python&&C++&&Node.js&&C语言)

请实现一个简易内存池 , 根据请求命令完成内存分配和释放。
内存池支持两种操作命令,REQUEST和RELEASE,其格式为:
REQUEST=请求的内存大小 表示请求分配指定大小内存,如果分配成功,返回分配到的内存首地址;如果内存不足,或指定的大小为 0 ,则输出error。
RELEASE=释放的内存首地址 表示释放掉之前分配的内存,释放成功无需输出,如果释放不存在的首地址则输出error。
注意:
1. 内存池总大小为 100 字节。
2. 内存池地址分配必须是连续内存,并优先从低地址分配。
3. 内存释放后可被再次分配,已释放的内存在空闲时不能被二次释放。
4. 不会释放已申请的内存块的中间地址。
5. 释放操作只是针对首地址所对应的单个内存块进行操作,不会影响其它内存块。

输入描述:

 

·首行为整数N ,表示操作命令的个数,取值范围:0 < N <= 100。

接下来的N行,每行将给出一个操作命令,操作命令和参数之间用 “=”分割。

输出描述:

 

见题面输出要求

示例1 输入输出示例仅供调试,后台判题数据一般不包含示例

输入

2
REQUEST=10
REQUEST=20

输出

0
10

示例2 输入输出示例仅供调试,后台判题数据一般不包含示例

输入

5
REQUEST=10
REQUEST=20
RELEASE=0
REQUEST=20
REQUEST=10

输出

0
10
30
0

说明

第一条指令,申请地址0~9的10个字节内存,返回首地址0
第二条指令,申请地址10~29的20字节内存,返回首地址10
第三条指令,释放首地址为0的内存申请,0~9地址内存被释放,变为空闲,释放成功,无需输出
第四条指令,申请20字节内存,0~9地址内存连续空间不足20字节,往后查找到30~49地址,返回首地址30
第五条指令,申请10字节,0~9地址内存空间足够,返回首地址0

Java版本

import java.util.Scanner;

public class ErrorCalculator {
    private static final String STR_REQUEST = "REQUEST";
    private static final String ERR_RESULT = "error";
    private static int[] memory = new int[101];
    private static int[] nums = new int[101];

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int row = Integer.parseInt(scanner.nextLine().trim());
        String[] requests = new String[row];
        for (int i = 0; i < row; i++) {
            requests[i] = scanner.nextLine().trim();
        }
        scanner.close();

        for (String elem : requests) {
            instructProcess(elem);
        }
    }

    private static boolean calcError(String strLeft, int length) {
        if (strLeft.equals(STR_REQUEST)) {
            int index = -1;
            int count = 0;
            if (length == 0) {
                System.out.println(ERR_RESULT);
                return true;
            }
            for (int i = 0; i < memory.length - 1; i++) {
                if (memory[i] != 0) {
                    count = 0;
                } else {
                    count += 1;
                }
                if (count != length) {
                    continue;
                } else {
                    index = i - count + 1;
                    break;
                }
            }
            if (index == -1) {
                System.out.println(ERR_RESULT);
                return true;
            }
            System.out.println(index);
            nums[index] = count;
            int j = index;
            while (j < index + count) {
                memory[j] = 1;
                j += 1;
            }
            return true;
        }
        return false;
    }

    private static void instructProcess(String elem) {
        String[] tmpList = elem.split("=");
        String strLeft = tmpList[0].toUpperCase();
        int length = Integer.parseInt(tmpList[1].trim());
        boolean flag = calcError(strLeft, length);
        if (flag) {
            return;
        }
        if (memory[length] == 0) {
            System.out.println("error");
            return;
        }
        for (int i = length; i < length + nums[length]; i++) {
            memory[i] = 0;
        }
    }
}

Python版本

def calc_error(str_left, length):
    if str_left == STR_REQUEST:
        index, count = -1, 0
        if length == 0:
            print(ERR_RESULT)
            return True
        for i in range(len(memory) - 1):
            if memory[i] != 0:
                count = 0
            else:
                count += 1
            if count != length:
                continue
            else:
                index = i - count + 1
                break
        if index == -1:
            print(ERR_RESULT)
            return True
        print(index)
        nums[index] = count
        j = index
        while j < index + count:
            memory[j] = 1
            j += 1
        return True


def instruct_process(elem):
    tmp_list = elem.split("=")
    str_left = tmp_list[0].upper()
    length = int(tmp_list[1])
    flag = calc_error(str_left, length)
    if flag:
        return
    if memory[length] == 0:
        print("error")
        return
    for i in range(length, length + nums[length]):
        memory[i] = 0


if __name__ == "__main__":
    STR_REQUEST = "REQUEST"
    ERR_RESULT = "error"
    row = int(input().strip())
    requests = [input().strip() for _ in range(row)]
    memory = [0] * 101
    nums = [0] * 101
    for elem in requests:
        instruct_process(elem)

C++版本

#include <iostream>
#include <vector>
#include <sstream>

const std::string STR_REQUEST = "REQUEST";
const std::string ERR_RESULT = "error";

std::vector<int> memory(101, 0);
std::vector<int> nums(101, 0);

bool calcError(const std::string& strLeft, int length) {
    if (strLeft == STR_REQUEST) {
        int index = -1;
        int count = 0;
        if (length == 0) {
            std::cout << ERR_RESULT << std::endl;
            return true;
        }
        for (int i = 0; i < memory.size() - 1; i++) {
            if (memory[i] != 0) {
                count = 0;
            } else {
                count += 1;
            }
            if (count != length) {
                continue;
            } else {
                index = i - count + 1;
                break;
            }
        }
        if (index == -1) {
            std::cout << ERR_RESULT << std::endl;
            return true;
        }
        std::cout << index << std::endl;
        nums[index] = count;
        int j = index;
        while (j < index + count) {
            memory[j] = 1;
            j += 1;
        }
        return true;
    }
    return false;
}

void instructProcess(const std::string& elem) {
    std::istringstream iss(elem);
    std::string strLeft;
    int length;
    iss >> strLeft >> length;

    bool flag = calcError(strLeft, length);
    if (flag) {
        return;
    }
    if (memory[length] == 0) {
        std::cout << "error" << std::endl;
        return;
    }
    for (int i = length; i < length + nums[length]; i++) {
        memory[i] = 0;
    }
}

int main() {
    int row;
    std::cin >> row;
    std::cin.ignore();

    std::vector<std::string> requests(row);
    for (int i = 0; i < row; i++) {
        std::getline(std::cin, requests[i]);
    }

    for (const auto& elem : requests) {
        instructProcess(elem);
    }

    return 0;
}

C语言版本

#include <stdio.h>
#include <string.h>

#define STR_REQUEST "REQUEST"
#define ERR_RESULT "error"

int memory[101] = {0};
int nums[101] = {0};

int calcError(const char *strLeft, int length) {
    if (strcmp(strLeft, STR_REQUEST) == 0) {
        int index = -1;
        int count = 0;
        if (length == 0) {
            printf("%s\n", ERR_RESULT);
            return 1;
        }
        for (int i = 0; i < 100; i++) {
            if (memory[i] != 0) {
                count = 0;
            } else {
                count += 1;
            }
            if (count != length) {
                continue;
            } else {
                index = i - count + 1;
                break;
            }
        }
        if (index == -1) {
            printf("%s\n", ERR_RESULT);
            return 1;
        }
        printf("%d\n", index);
        nums[index] = count;
        int j = index;
        while (j < index + count) {
            memory[j] = 1;
            j += 1;
        }
        return 1;
    }
    return 0;
}

void instructProcess(const char *elem) {
    char *tmpList[2];
    char *token = strtok(elem, "=");
    int i = 0;
    while (token != NULL) {
        tmpList[i++] = token;
        token = strtok(NULL, "=");
    }
    char *strLeft = tmpList[0];
    int length = atoi(tmpList[1]);
    int flag = calcError(strLeft, length);
    if (flag) {
        return;
    }
    if (memory[length] == 0) {
        printf("error\n");
        return;
    }
    for (int i = length; i < length + nums[length]; i++) {
        memory[i] = 0;
    }
}

int main() {
    int row;
    scanf("%d", &row);
    char requests[row][100];
    for (int i = 0; i < row; i++) {
        scanf("%s", requests[i]);
    }

    for (int i = 0; i < row; i++) {
        instructProcess(requests[i]);
    }
    return 0;
}

Node.js版本

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const STR_REQUEST = "REQUEST";
const ERR_RESULT = "error";

const memory = Array(101).fill(0);
const nums = Array(101).fill(0);

function calcError(strLeft, length) {
  if (strLeft === STR_REQUEST) {
    let index = -1;
    let count = 0;
    if (length === 0) {
      console.log(ERR_RESULT);
      return true;
    }
    for (let i = 0; i < 100; i++) {
      if (memory[i] !== 0) {
        count = 0;
      } else {
        count += 1;
      }
      if (count !== length) {
        continue;
      } else {
        index = i - count + 1;
        break;
      }
    }
    if (index === -1) {
      console.log(ERR_RESULT);
      return true;
    }
    console.log(index);
    nums[index] = count;
    let j = index;
    while (j < index + count) {
      memory[j] = 1;
      j += 1;
    }
    return true;
  }
  return false;
}

function instructProcess(elem) {
  const [strLeft, length] = elem.split("=");
  const flag = calcError(strLeft, parseInt(length));
  if (flag) {
    return;
  }
  if (memory[length] === 0) {
    console.log("error");
    return;
  }
  for (let i = length; i < length + nums[length]; i++) {
    memory[i] = 0;
  }
}

rl.question('Enter the number of requests: ', (row) => {
  const requests = [];
  let count = 0;
  const readRequests = () => {
    if (count < row) {
      rl.question(`Enter request ${count + 1}: `, (request) => {
        requests.push(request);
        count++;
        readRequests();
      });
    } else {
      rl.close();
      requests.forEach(instructProcess);
    }
  };
  readRequests();
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值