Queue和Stack的初始化

Queue

  • queue.isEmpty() :判断队列是否为空。为空返回true,不为空返回false。
  • queue.peek(): 判断队头元素是否为空。为空返回null,不为空返回栈顶元素。
  • queue.size():为空返回0,不为空返回一个大于1的整数。

[ 判断是否为空一般用 Q != null + Q.isEmpty() ]
如果保证了已经 Q = new Queue; 则直接 Q.isEmpty()

		//Queue<Integer> queue1  (类变量)
        System.out.println( queue1 == null);  // true
        System.out.println(queue1.size() == 0 ); //出错!!因为 queue1 is null
        
        Queue<Integer> queue2 = new ArrayDeque<>();
        System.out.println(queue2 == null); //false
        System.out.println(queue2.isEmpty()); //true
        System.out.println(queue2.size() == 0 ); //true

Stack

stack.empty():为空返回true,不为空返回false。
stack.isEmpty() :为空返回true,不为空返回false(与stack.empty()无结果上的区别)。
stack.peek() :为空返回null,不为空返回栈顶元素。
stack.size(): 为空返回0,不为空返回一个大于1的整数。

————————————————
原文链接:https://blog.csdn.net/weixin_45744426/article/details/103665332

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言栈的初始化及基本操作: 1. 栈的初始化: ```c #define MAXSIZE 100 typedef struct { int data[MAXSIZE]; int top; } Stack; void initStack(Stack *s) { s->top = -1; } ``` 2. 进栈操作: ```c int push(Stack *s, int x) { if (s->top == MAXSIZE - 1) { return 0; // 栈满 } s->data[++(s->top)] = x; return 1; } ``` 3. 出栈操作: ```c int pop(Stack *s, int *x) { if (s->top == -1) { return 0; // 栈空 } *x = s->data[s->top--]; return 1; } ``` 队列初始化及基本操作: 1. 队列初始化: ```c #define MAXSIZE 100 typedef struct { int data[MAXSIZE]; int front, rear; } Queue; void initQueue(Queue *q) { q->front = q->rear = 0; } ``` 2. 进队列操作: ```c int enQueue(Queue *q, int x) { if ((q->rear + 1) % MAXSIZE == q->front) { return 0; // 队列满 } q->data[q->rear] = x; q->rear = (q->rear + 1) % MAXSIZE; return 1; } ``` 3. 出队列操作: ```c int deQueue(Queue *q, int *x) { if (q->front == q->rear) { return 0; // 队列空 } *x = q->data[q->front]; q->front = (q->front + 1) % MAXSIZE; return 1; } ``` 实验总结与思考: 在本次实验中,我学会了如何初始化和操作栈和队列。栈和队列都是非常常用的数据结构,它们可以用于很多场景,如括号匹配、表达式求值、迷宫搜索等等。在实现栈和队列的基本操作时,需要注意数据结构的定义和边界条件的判断。同时,我们还学习了如何使用结构体来定义栈和队列,这使得代码结构更加清晰。通过这次实验,我对数据结构的理解更加深入了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值