java queue队列的增删改查用法

offer,add 区别:

一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,多出的项就会被拒绝。

这时新的 offer 方法就可以起作用了。它不是对调用 add() 方法抛出一个 unchecked 异常,而只是得到由 offer() 返回的 false。

poll,remove 区别:

remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似, 但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况。

peek,element区别:

element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是用C实现队列增删改查的示例代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct { int data[MAX_SIZE]; // 存储数据的数组 int front; // 队头指针 int rear; // 队尾指针 } Queue; // 初始化队列 void initQueue(Queue *q) { q->front = q->rear = 0; } // 判断队列是否为空 int isEmpty(Queue *q) { return (q->front == q->rear); } // 判断队列是否已满 int isFull(Queue *q) { return ((q->rear + 1) % MAX_SIZE == q->front); } // 入队操作 void enqueue(Queue *q, int x) { if (isFull(q)) { printf("Queue is full.\n"); return; } q->data[q->rear] = x; q->rear = (q->rear + 1) % MAX_SIZE; } // 出队操作 void dequeue(Queue *q) { if (isEmpty(q)) { printf("Queue is empty.\n"); return; } q->front = (q->front + 1) % MAX_SIZE; } // 取队头元素 int getFront(Queue *q) { if (isEmpty(q)) { printf("Queue is empty.\n"); return -1; } return q->data[q->front]; } // 取队尾元素 int getRear(Queue *q) { if (isEmpty(q)) { printf("Queue is empty.\n"); return -1; } return q->data[(q->rear - 1 + MAX_SIZE) % MAX_SIZE]; } // 打印队列元素 void printQueue(Queue *q) { if (isEmpty(q)) { printf("Queue is empty.\n"); return; } printf("Queue elements: "); int i = q->front; while (i != q->rear) { printf("%d ", q->data[i]); i = (i + 1) % MAX_SIZE; } printf("\n"); } int main() { Queue q; initQueue(&q); enqueue(&q, 1); enqueue(&q, 2); enqueue(&q, 3); printQueue(&q); printf("Front element: %d\n", getFront(&q)); printf("Rear element: %d\n", getRear(&q)); dequeue(&q); printQueue(&q); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值