delphi 写一个队列 能从队列中添加数据,和读取数据
时间: 2024-02-09 09:10:02 浏览: 27
好的,以下是一个简单的 Delphi 队列实现:
```delphi
unit QueueUnit;
interface
type
TQueue = class
private
FData: array of Integer;
FHead: Integer;
FTail: Integer;
FCount: Integer;
FCapacity: Integer;
function GetCapacity: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Enqueue(AValue: Integer);
function Dequeue: Integer;
property Count: Integer read FCount;
property Capacity: Integer read GetCapacity;
end;
implementation
constructor TQueue.Create;
begin
inherited;
FCount := 0;
FCapacity := 8;
SetLength(FData, FCapacity);
FHead := 0;
FTail := 0;
end;
destructor TQueue.Destroy;
begin
SetLength(FData, 0);
inherited;
end;
procedure TQueue.Enqueue(AValue: Integer);
begin
if FCount = FCapacity then
begin
FCapacity := FCapacity * 2;
SetLength(FData, FCapacity);
end;
FData[FTail] := AValue;
FTail := (FTail + 1) mod FCapacity;
Inc(FCount);
end;
function TQueue.Dequeue: Integer;
begin
if FCount = 0 then
raise Exception.Create('Queue is empty');
Result := FData[FHead];
FHead := (FHead + 1) mod FCapacity;
Dec(FCount);
end;
function TQueue.GetCapacity: Integer;
begin
Result := Length(FData);
end;
end.
```
使用示例:
```delphi
var
Queue: TQueue;
I: Integer;
begin
Queue := TQueue.Create;
try
Queue.Enqueue(1);
Queue.Enqueue(2);
Queue.Enqueue(3);
while Queue.Count > 0 do
begin
I := Queue.Dequeue;
Writeln(I);
end;
finally
Queue.Free;
end;
end.
```
以上代码实现了一个基于数组的队列,可以通过 `Enqueue` 方法向队列中添加数据,通过 `Dequeue` 方法从队列中读取数据。注意,如果队列为空,调用 `Dequeue` 方法会抛出异常。