帮我看看这段代码的问题,谢谢

P3613 【深基15.例2】寄包柜

MAOSICHENG @ 2023-11-25 16:44:08

#include<iostream>
#include<malloc.h>
using namespace std;

typedef struct cabinet
{
    int ID;
    long long data;
    struct cabinet* next;
}Cabinet;

Cabinet* cabinet_list[100005];//写一个寄存柜的数组

void add_cabinet_cell(int i,int j, int k)
{
    Cabinet* newcabinet = (Cabinet*)malloc(sizeof(Cabinet));
    newcabinet->ID = j;
    newcabinet->data = k;
    if (cabinet_list[i] == NULL)
    {
        cabinet_list[i] = newcabinet;
    }
    else
    {
        Cabinet* lastcabinet = cabinet_list[i];
        while (lastcabinet->next != NULL)
        {
            if (lastcabinet->ID == j)
            {
                lastcabinet->data = k;
            }
            else
            {
                if ((lastcabinet->next)->next == NULL)
                {
                    (lastcabinet->next)->next = newcabinet;
                    break;
                }
                else 
                {
                    lastcabinet = lastcabinet->next;
                }
            }
        }
    }
}

long long look_up_num(int i,int j)
{
    Cabinet* newcabinet = (Cabinet*)malloc(sizeof(Cabinet));
    newcabinet = cabinet_list[i];
    while (newcabinet->ID != j)
    {
        newcabinet = newcabinet->next;
    }
    return newcabinet->data;
}

int main()
{
    int n = 0, q = 0;
    cin >> n >> q;
    for (int i1 = 0; i1 < n; i1++)
    {
        int n = 0;
        int i = 0, j = 0, k = 0;
        cin >> n;
        switch (n)
        {
        case 1:
            cin >> i >> j >> k;
            add_cabinet_cell(i, j, k);
            break;
        case 2:
            cin >> i >> j;
            cout << look_up_num(i, j) << endl;
        }
    }
    for (int i = 0; i < 100005; i++)
    {
        Cabinet* current = cabinet_list[i];
        while (current != NULL)
        {
            Cabinet* next = current->next;
            free(current);
            current = next;
        }
        cabinet_list[i] = NULL;
    }
}

by jqQt0220 @ 2023-11-25 16:44:41

不如 vector


by MAOSICHENG @ 2023-12-07 12:14:38

不太会,可以帮我看看我的问题吗?


|