簡體   English   中英

如何將 int 與 C 中的隊列進行比較?

[英]How do I compare an int to a queue in C?

假設 enqueue 正確地將一個數字添加到隊列中。 因此我的隊列應該是 {1,2,3,4}。
另外,我意識到這是很多代碼。 我相信問題出在主要的 function 上。 編輯:我按照一些人的要求發布了整個代碼,但我意識到這對於非專業人士來說可能看起來非常復雜。 我只是想將隊列的內容與 integer 進行比較。

// C program for array implementation of queue
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// A structure to represent a queue
struct Queue
{
int front, rear, size;
unsigned capacity;
int* array;
};

// function to create a queue of given capacity.
// It initializes size of queue as 0
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;  // This is important, see the enqueue
queue->array = (int*) malloc(queue->capacity * sizeof(int));
return queue;
}

// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{  return (queue->size == queue->capacity);  }

// Queue is empty when size is 0
int isEmpty(int Queue* queue)
{  return (queue->size == 0); }

// Function to add an item to the queue.
// It changes rear and size
void enqueue(struct Queue* queue, int item)
{
if (isFull(queue))
    return;
queue->rear = (queue->rear + 1)%queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("%d enqueued to queue\n", item);
}

// Function to remove an item from queue.
// It changes front and size
int dequeue(int Queue queue)
{
if (isEmpty(queue))
    return INT_MIN;
int item = queue->array[queue->front];
queue->front = (queue->front + 1)%queue->capacity;
queue->size = queue->size - 1;
return item;
}

// Function to get front of queue
int front(int Queue queue)
{
if (isEmpty(queue))
    return INT_MIN;
return queue->array[queue->front];
}

// Function to get rear of queue
int rear(int Queue queue)
{
if (isEmpty(queue))
    return INT_MIN;
return queue->array[queue->rear];
}

int main()
{
    struct Queue* queue = createQueue(1000);
    enqueue(queue, 1);
    enqueue(queue, 2);
    enqueue(queue, 3);
    enqueue(queue, 4);
    int tag = 2;
    if (queue[0] = tag){ //if the first element of queue is 2, it should print. It is not.
        printf("Your first element of your queue is 2");
    }
    if (tag = queue[1]){ //this should print because the first element of queue is 2!
        printf("Your first element of your queue is 2");
    }
}

錯誤:

從“int”類型分配給“struct Queue”類型時的類型不兼容

錯誤消息清楚地指出:您正在分配而不是比較.

將條件更改為

if (queue[0] == tag) {

if (tag == queue[1]) {

相等的比較運算符是== ,而不是=

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM