数据结构-队列:C++中的“先来先服务”法则

引言

在C++的编程宇宙中,数据结构如同银河系里的恒星,照亮着我们的代码之路,让程序运行得更加顺畅和高效。队列,作为众多数据结构中的一员,遵循着“先来先服务”(First In First Out, FIFO)的原则,如同车站的队伍,先到的人先上车。今天,我们将一起探索队列的奥秘,看看它如何在算法世界中扮演重要角色。

技术概述

定义与简介

队列是一种线性数据结构,它只允许在队尾(rear)进行插入操作,在队首(front)进行删除操作。这种结构确保了元素的顺序性,即最先加入队列的元素将最先被处理。

核心特性和优势

  • FIFO原则:队列严格遵守“先来先服务”的原则,确保数据的处理顺序。
  • 操作简便:队列的插入(enqueue)和删除(dequeue)操作相对简单,时间复杂度通常为O(1)。
  • 应用场景广泛:从操作系统中的任务调度,到网络通信中的数据包处理,队列都是不可或缺的工具。

示例代码

让我们通过一段C++代码来看看如何实现一个简单的队列:

#include <iostream>
#include <list>

class SimpleQueue {
   
   
private:
    std::list<int> data;

public:
    void enqueue(int value) {
   
   
        data.push_back(value);
    }

    int dequeue() {
   
   
        if (data.empty()) {
   
   
            std::cerr << "Error: Queue is empty.\n";
            return -1;
        }
        int frontValue = data.front();
        data.pop_front();
        return frontValue;
    }

    bool isEmpty() const {
   
   
        return data.empty
先来先服务算法 #include "stdio.h" #include #define max 100 #define pfree 0 /*process end*/ #define running 1 /*process running status*/ #define aready 2 /*process aready status */ #define blocking 3 /*process aready blocking status*/ typedef struct node { char name; int status; int ax,bx,cx,dx; int pc; int psw; struct node *next; /*pcb define*/ }pcb; pcb *createprocess(pcb *head) { pcb *p,*q; int a,b,c,d,m,n; char ID; q=NULL; printf("input the first seven status pcb:"); scanf("\n%c%d%d%d%d%d%d",&ID,&a,&b,&c,&d,&m,&n); while(1) { p=(pcb*)malloc(sizeof(pcb)); p->name=ID; p->ax=a; p->bx=b; p->cx=c; p->dx=d; p->pc=m; p->psw=n; p->status=aready; if(head==NULL) head=p; else q->next=p; q=p; printf("input the next seven status pcb: "); scanf("\n%c",&ID); if (ID == '*') break; scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&m,&n); } if(q!=NULL) q->next=NULL; q=head; while(q) { printf("\n process name. status.ax. bx. cx. dx. pc. psw.\n "); printf("%10c%5d%5d%5d%5d%5d%5d%5d",q->name,q->status,q->ax,q->bx,q->cx,q->dx,q->pc,q->psw); q=q->next; } return head;/*createprocess end*/ } void processfcfs(pcb *head) /*use fifo */ { pcb *p; p=head; printf("\n the process use fcfs method.\n"); printf("running the frist process:\n"); while(p!=NULL) { p->status=running; printf("\nprocess name status. ax. bx. cx. dx. pc. psw."); printf("\n%10c%5d%8d%5d%5d%5d%5d%5d",p->name,p->status,p->ax,p->bx,p->cx,p->dx,p->pc,p->psw); /*check process running status */ p->status=0; p=p->next; } printf("\n检查进程是否结束:"); p=head; while(p) { printf("\n%3c%3d",p->name,p->status); p=p->next; } printf("\ngame is over!\n"); } main() { pcb *head; head=NULL; head=createprocess(head); processfcfs(head); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值