一起创业网-为互联网创业者服务

排队等候程序怎么写

排队等候程序的基本实现通常包括以下几个关键步骤:

初始化队列

创建一个空队列,用于存储排队的对象。可以使用数组或链表等数据结构来实现队列。

入队操作

将需要排队的对象加入队列。入队操作将对象放置在队列的末尾,并更新队列的长度。

出队操作

从队列中取出排在最前面的对象。出队操作将对象从队列的头部移除,并更新队列的长度。

查询队列长度

获取当前队列中的对象数量。

查询排队情况

根据需求,可以实现查询当前队列中的对象信息,如排队号码、等待时间等。

处理等待事件

在多线程或多进程环境中,需要处理等待事件和唤醒进程。例如,使用等待队列来管理等待的进程,并在有新的任务到来时唤醒它们。

```csharp

using System;

using System.Collections.Generic;

class BankQueueApp

{

private static Queue queue = new Queue();

private static int maxsize = 10;

private static int front = -1;

private static int rear = -1;

public static void Main()

{

Console.WriteLine("请选择存储结构的类型:1.顺序队列 2.链队列");

char seleflag = Convert.ToChar(Console.ReadLine());

if (seleflag == '1')

{

maxsize = 10;

}

else

{

maxsize = int.Parse(Console.ReadLine());

}

EnQueue(1);

EnQueue(2);

EnQueue(3);

while (true)

{

Console.WriteLine("1. 出队");

Console.WriteLine("2. 查询队列长度");

Console.WriteLine("3. 退出");

Console.Write("请输入选项: ");

int choice = int.Parse(Console.ReadLine());

switch (choice)

{

case 1:

if (DeQueue())

{

Console.WriteLine("出队成功,当前队列为空。");

}

else

{

Console.WriteLine("队列为空,无法出队。");

}

break;

case 2:

Console.WriteLine("当前队列长度为: " + queue.Count);

break;

case 3:

Console.WriteLine("退出程序。");

return;

default:

Console.WriteLine("无效的选项,请重新输入。");

break;

}

}

}

public static bool EnQueue(int elem)

{

if (IsFull())

{

Console.WriteLine("队列已满,无法入队。");

return false;

}

if (front == -1 && rear == maxsize - 1)

{

rear = (rear + 1) % maxsize;

}

else

{

rear = (rear + 1) % maxsize;

}

queue.Enqueue(elem);

Console.WriteLine("入队成功,当前队列长度为: " + queue.Count);

return true;

}

public static bool DeQueue()

{

if (IsEmpty())

{

Console.WriteLine("队列为空,无法出队。");

return false;

}

front = (front + 1) % maxsize;

Console.WriteLine("出队成功,当前队列为空。");

return true;

}

public static bool IsFull()

{

return (rear + 1) % maxsize == front;

}

public static bool IsEmpty()

{

return front == -1;

}

}

```

这个示例代码实现了一个简单的顺序队列,支持入队、出队、查询队列长度等基本操作。可以根据具体需求进行扩展和优化,例如添加优先级、时间限制、限制人数等功能。