队列(链表实现)及其相关操作

队列
一种特殊的表
特殊之处:插入时只能在表尾插入,出表时只能在表头取出,
也就是(先进先出)

队列的定义(链表实现)

typedef int QDataType;

typedef struct QNode{
 struct QNode* _next;
 QDataType _data;
}QNode;

typedef struct Queue{
 QNode* _front;//头指针
 QNode* _rear;//尾指针
 int _size;//有效长度
}Queue;

初始化

void queueInit(Queue* q){
 //初始化空队列
 q->_front = q->_rear = NULL;
 q->_size = 0;
}

创建新的结点

QNode* creatNode(QDataType data){
 QNode* node = (QNode*)malloc(sizeof(QNode));
 node->_data = data;
 node->_next = NULL;
 return node;
}

入队操作(链表的尾插)

void queuePush(Queue* q, QDataType data){
 QNode* node = creatNode(data);
 //空队列
 if (q->_front == NULL) {
  q->_front = q->_rear = node;
 }
 else{
  //把新的结点与整个链表连接起来
  q->_rear->_next = node;
  q->_rear = node;
 }
 q->_size++;
}

出队(链表的头删操作)

void queuePop(Queue* q){
 if (q->_front){
  QNode* next = q->_front->_next;
  free(q->_front);
  q->_front = next;
  //删除之后是否为空表
  if (q->_front == NULL) {
   q->_rear = NULL;
  }
  q->_size--;
 }
}

获取队头元素

QDataType queueFront(Queue* q){
 return q->_front->_data;
}

获取队尾元素

QDataType queueBack(Queue* q){
 return q->_rear->_data;
}

返回队列中有效长度

int queueSize(Queue* q){
 return q->_size;
}

判断队列是否为空(为空返回0,否则返回1)

int queueEmpty(Queue* q){
 if (q->_front == NULL) {
  return 1
 }
 return 0;
}

销毁栈

void queueDestory(Queue* q){
 QNode* cur = q->_front;
 while (cur){
  QNode* next = cur->_next;
  free(cur);
  cur = next;
 }
 q->_front = q->_rear = NULL;
 q->_size = 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值