c# - 出队方法 C#
问题描述
我设计了一个简单的 Windows 窗体应用程序,用户在其中输入他的姓名并单击添加,这会将他的姓名添加到队列中。还有一个删除按钮,按下它会使他的名字出队。
我面临的障碍是出队时,“head”值按预期增加,numItem 按预期减少,但名称不会从队列中删除。
代码:
队列类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssessedExerciseWeek1_2_Task1A
{
class Queue
{
private readonly int maxsize = 10;
private string[] store;
private int head = 0;
private int tail = 0;
private int numItems;
public Queue()
{
store = new string[maxsize];
}
public Queue(int size)
{
maxsize = size;
store = new string[maxsize];
}
public void Enqueue(string value)
{
numItems++;
store[tail] = value;
if (++tail == maxsize)
{
tail = 0;
}
}
public string Dequeue()
{
string headItem;
numItems--;
headItem = store[head];
if (++head == maxsize)
{
head = 0;
}
return headItem;
}
public bool IsEmpty()
{
return tail == 0; //returns the boolean result of the comparison between head and 0
}
public bool IsFull()
{
return tail == maxsize;
}
public int CountQueue() //counts the number of items inside the queue
{
return tail - head;
}
public int Tail //property
{
set { this.tail = value; }
get { return tail; }
}
}
}
删除按钮代码:
private void RemoveButton_Click(object sender, EventArgs e)
{
names.Dequeue(); //names is a new instance of the queue (declared on top of the windows form code)
}
解决方案
用数组实现这一点不是最好的选择,但如果你想这样做,那么问题是如果数组的“空间”为空,你现在没有定义一种方法。我使用 null 来实现这一点。将您的出队方法更改为:
public string Dequeue()
{
string headItem;
headItem = store[head];
if (headItem != null)
{
store[head] = null;
numItems--;
if (++head == maxsize)
head = 0;
}
return headItem ?? "There are no more objects in the queue";
}
您可能会考虑向 Enqueue() 方法添加验证,以确保如果数组已满,则不会添加新字符串,因为目前,当超过最大大小时,您的第一个元素会被覆盖。
此外,请检查实现此功能的不同方法,例如使用 LinkedList,如评论中所建议的那样,或创建您自己的 Node 类来“连接”对象。
推荐阅读
- android - 工具使用方法:openDrawer = "bottom"
- c - C 语言 K60 系列 GPIO 键盘
- php - Php mysql - 获取最后几天的值和条目总数
- java - 执行 ApplciationRunner 仅在开发配置文件中运行
- reactjs - 接受 TextArea 和 Input 的 onChange 的 Typescript 和 React 组件
- c - 如何在C中重置字符串
- c# - 带线程的套接字循环
- sqlalchemy - 气流安装 | Ansible
- pandas - 用 cumsum 填充连续的 NaN,在每个连续的 NaN 上加一
- amazon-redshift - 将日期名称转换为数字-例如-星期一到 1