1. 程式人生 > >360 校招記憶體管理Java版

360 校招記憶體管理Java版

package Easy;

import java.util.Scanner;

public class Three2 {
    public static void main(String[] args) {
        Three2 t = new Three2();
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        int maxMem = in.nextInt();
        int handleNum = 1;
        Mem head = t.getMemInstance();
        while
(in.hasNext()){ String operation = in.next(); if(operation.equals("def")){ //整理記憶體不做任何輸出 Mem p = head; while(p.next!=null){ if(p.next.isDel){ p.next=p.next.next; }else
{ p=p.next; } } }else if(operation.equals("new")){ //申請記憶體,成功返回控制代碼值,失敗返回NULL int size = in.nextInt(); Mem node = t.getMemInstance(); node.size = size; Mem p = head; Mem begin = head; Mem end = head; int
totalUsed=0; int innerCan = 0; while(p!=null){ totalUsed += p.size; if(p.isDel){ end = p; innerCan += p.size; }else{ begin = p; innerCan = 0; } if(innerCan>=size){ end = end.next; break; } if(p.next!=null){ p=p.next; }else{ break; } } if(innerCan>size){ Mem newNode1 = t.getMemInstance(); newNode1.size = size; newNode1.handleNo = handleNum; System.out.println(handleNum); handleNum++; Mem newNode2 = t.getMemInstance(); newNode2.size = innerCan-size; newNode2.handleNo = -1; newNode2.isDel = true; newNode1.next = newNode2; newNode2.next = end; begin.next = newNode1; }else if(innerCan==size){ Mem newNode = t.getMemInstance(); newNode.size = size; newNode.handleNo = handleNum; System.out.println(handleNum); newNode.next=begin.next; begin.next=newNode; handleNum++; }else if(maxMem-totalUsed>=size){ Mem newNode = t.getMemInstance(); newNode.size = size; newNode.handleNo = handleNum; System.out.println(handleNum); handleNum++; p.next=newNode; }else{ System.out.println("NULL"); } }else if(operation.equals("del")){ //釋放控制代碼指向的記憶體,失敗返回ILLEGAL_OPERATION,成功無輸出 int index = in.nextInt(); Mem p = head; boolean canDel = false; if(index<handleNum){ while(p!=null){ if(p.handleNo==index){ if(!p.isDel){ p.isDel=true; canDel = true; } break; } p=p.next; } } if(!canDel){ System.out.println("ILLEGAL_OPERATION"); } } } } private Mem getMemInstance(){ return new Mem(); } class Mem{ public int size=0; public int handleNo=-1; public Mem next = null; public boolean isDel = false; } }