thoga31

Stack Class

Jul 17th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.47 KB | None | 0 0
  1. {$mode objfpc}
  2. program Stack_Class;
  3. uses sysutils;
  4.  
  5. type generic TStack<T> = class(TObject)
  6.          private
  7.              const MINIMUM = 32;
  8.              var data : array of T;
  9.                  top : word;
  10.          public
  11.              function Pop : T;
  12.              procedure Push(value : T);
  13.              function IsEmpty : boolean;
  14.              constructor Create;
  15.              constructor Create(limit : word); overload;
  16.      end;
  17.  
  18.  
  19. constructor TStack.Create();
  20. begin
  21.     self.Create(self.MINIMUM);
  22. end;
  23.  
  24. constructor TStack.Create(limit : word); overload;
  25. begin
  26.     if limit <= 0 then limit := self.MINIMUM;
  27.     SetLength(self.data, limit);
  28.     self.top := 0;
  29. end;
  30.  
  31. procedure TStack.Push(value : T);
  32. begin
  33.     inc(self.top);
  34.     if self.top > length(self.data) then SetLength(self.data, Length(self.data)*2);
  35.     self.data[self.top-1] := value;
  36. end;
  37.  
  38. function TStack.Pop : T;
  39. begin
  40.     Pop := self.data[self.top-1];
  41.     dec(self.top);
  42. end;
  43.  
  44. function TStack.IsEmpty : boolean;
  45. begin
  46.     IsEmpty := (self.top = 0);
  47. end;
  48.  
  49. type TIntegerStack = specialize TStack<Integer>;
  50. var s : TIntegerStack;
  51.     i : integer;
  52. begin
  53.     try
  54.         s := TIntegerStack.Create;
  55.         for i in [1..10] do s.Push(i);
  56.         while not s.IsEmpty do write(s.Pop, ', ');
  57.         writeln('FIM');
  58.         s.Free;
  59.     except
  60.         on ex:exception do begin
  61.             writeln; writeln(upcase(ex.classname), ': ', ex.message);
  62.         end;
  63.     end;
  64.     readln;
  65. end.
Advertisement
Add Comment
Please, Sign In to add comment