优先级队列数组(c)

时间:2012-09-30 18:22:34

标签: c struct priority-queue

我正在构建一个优先级队列,但是我没有用整数填充PQ数组,而是指定了一个结构的指针。下面是PQ的两个结构,初始化器和插入函数的代码:

typedef struct HeapStruct *PriorityQueue;
typedef struct Customer *CustomerP;

struct HeapStruct {
    int Capacity;
    int Size;
    int *Elements;
};

struct Customer {
    float arrivalT;
    float waitT;
    float departureT;
    float currentT;
    CustomerP *siblingR; //Used for linked list
};

PriorityQueue Initialize() {
    PriorityQueue H = (PriorityQueue) malloc(sizeof (struct HeapStruct));
    CustomerP sentinal = malloc(sizeof (struct Customer));
    sentinal->currentT = MinData;
    H->Capacity = 101;
    H->Size = 0;
    H->Elements[0] = &sentinal; //Syntax Error
    return H;
}

void Insert(CustomerP X, PriorityQueue H) {
    int i;
    if (IsFull(H)) {
        printf("Priority queue is full");
        return;
    }
    //Syntax errors
    for (i = ++H->Size; H->Elements[i/2]->currentT > X->currentT; i /= 2)
    H->Elements[i] = H->Elements[i/2];
    H->Elements[i] = X;
}

所以我试图在Int数组中放置一个指针并进行比较,例如H-> Elements [i] - > currentT,但我不知道如何处理指向数组中结构的指针并从那里访问结构。

任何人都可以帮我解决这个问题吗?如果需要,我很乐意提供更多信息。

3 个答案:

答案 0 :(得分:2)

你想要Eements

CustomerP*

然后你需要为H->Elements分配一些内存,以便我可以保存所有指针。

也许: -

H->Elements =  malloc(sizeof (CustomerP) * H->Capacity);

答案 1 :(得分:2)

Elements中的HeapStruct字段需要根据要存储在堆中的内容进行适当定义。然后,您需要在使用它之前为其分配内存。

所以第一个问题,堆中想要什么?你说你想要客户(不是int s,这就是你拥有的),但是你想要结构本身(Customer)或指向结构的指针(Customer *或{{1 }})。假设你想要后者:

CustomerP

然后你需要为它正确分配空间:

struct HeapStruct {
    int Capacity;
    int Size;
    CustomerP *Elements;
};

答案 2 :(得分:0)

H->Elements = (int *)malloc(sizeof(int));
H->Elements[0] = &sentinal;

OR     H-> Elements =& sentinal;

两者都应该有用。

相关问题