home *** CD-ROM | disk | FTP | other *** search
- {*********************************************************}
- {* AAIntDeq *}
- {* Copyright (c) Julian M Bucknall 2001 *}
- {* All rights reserved. *}
- {*********************************************************}
- {* Algorithms Alfresco: A deque for integers *}
- {*********************************************************}
-
- {Note: this unit is released as freeware. In other words, you are free
- to use this unit in your own applications, however I retain all
- copyright to the code. JMB}
-
- unit AAIntDeq;
-
- interface
-
- uses
- Classes;
-
- type
- TaaIntDeque = class
- private
- FList : TList;
- FHead : integer;
- FTail : integer;
- protected
- procedure idGrow;
- public
- constructor Create(aCapacity : integer);
- destructor Destroy; override;
-
- function IsEmpty : boolean;
-
- procedure Enqueue(aValue : integer);
- procedure Push(aValue : integer);
- function Pop : integer;
- end;
-
- implementation
-
- uses
- SysUtils;
-
- {===TaaIntDeque======================================================}
- constructor TaaIntDeque.Create(aCapacity : integer);
- begin
- inherited Create;
- FList := TList.Create;
- FList.Count := aCapacity;
- {let's help out the user of the deque by putting the head and tail
- pointers in the middle: it's probably more efficient}
- FHead := aCapacity div 2;
- FTail := FHead;
- end;
- {--------}
- destructor TaaIntDeque.Destroy;
- begin
- FList.Free;
- inherited Destroy;
- end;
- {--------}
- procedure TaaIntDeque.Enqueue(aValue : integer);
- begin
- FList.List^[FTail] := pointer(aValue);
- inc(FTail);
- if (FTail = FList.Count) then
- FTail := 0;
- if (FTail = FHead) then
- idGrow;
- end;
- {--------}
- procedure TaaIntDeque.idGrow;
- var
- OldCount : integer;
- i, j : integer;
- begin
- {grow the list by 50%}
- OldCount := FList.Count;
- FList.Count := (OldCount * 3) div 2;
- {expand the data into the increased space, maintaining the deque}
- if (FHead = 0) then
- FTail := OldCount
- else begin
- j := FList.Count;
- for i := pred(OldCount) downto FHead do begin
- dec(j);
- FList.List^[j] := FList.List^[i]
- end;
- FHead := j;
- end;
- end;
- {--------}
- function TaaIntDeque.IsEmpty : boolean;
- begin
- Result := FHead = FTail;
- end;
- {--------}
- procedure TaaIntDeque.Push(aValue : integer);
- begin
- if (FHead = 0) then
- FHead := FList.Count;
- dec(FHead);
- FList.List^[FHead] := pointer(aValue);
- if (FTail = FHead) then
- idGrow;
- end;
- {--------}
- function TaaIntDeque.Pop : integer;
- begin
- if FHead = FTail then
- raise Exception.Create('Integer deque is empty: cannot pop');
- Result := integer(FList.List^[FHead]);
- inc(FHead);
- if (FHead = FList.Count) then
- FHead := 0;
- end;
- {====================================================================}
-
- end.
-