delphi xe3中
Tstack = class(Tenumerable)
stack 后进先出;
TStack 表示相同类型的一种后进先出的数据结构,他可以是任意的大小,按你的需要扩展,同时你
也可以将“nil” push到栈里面;
当栈改变的时候 Tstack的onnotify 时间将会发生;
delphi xe3中 栈有如下几个属性以及事件:
count 表示栈当中所有条目;
clear 清空栈中所有的条目;
pop 将项目弹出栈并返回栈顶(空间复杂度为O(1)) 激发onnotify事件 同时count被减一(如果count已经是1了,将会激发异常)
push 将数据压入栈,同时count+1,同样会触发onnotify事件,如果有必要的话栈容量
(capacity)会自动增加;平常情况下push操作的空间复杂度为o(1)但是在容量必须增长的情况下为O(n),其中n为count
extract 移除并返回栈顶 ,count-1, 如果count已经是0,将会触发异常; 触发onnotify;空间复杂度为o(1);
trimexcess 设置容量与当前栈中的数据项目数相同,在很多数据项被删除以后比较有用
onnotify 当栈有项目被加入或者被移除的时候发生,这允许被移除的对象释放
辨析pop,extract
同样都是移除并返回数据项,但是触发onnotiy事件代码的时候一个是removed 一个是extracted
例子
procedure TForm3.Button1Click(Sender: TObject);
var
Stack: TStack;
begin
{ Create a new stack. }
Stack := TStack.Create();
{ Register a notification callback. }
Stack.OnNotify := StackChanged;
{ Push some items to the stack. }
Stack.Push('John');
Stack.Push('Mary');
Stack.Push('Bob');
Stack.Push('Anna');
Stack.Push('Erica');
{ Show the last pushed element without modifying the stack. }
MessageDlg('Last pushed element is: "' + Stack.Peek() + '".', mtInformation, [mbOK], 0);
{ Extract the top element: "John". }
Stack.Extract();
{ Reduce the capacity. }
Stack.TrimExcess();
{ The remaining count of elements }
MessageDlg('The stack contains ' + IntToStr(Stack.Count) + ' elements.', mtInformation, [mbOK], 0);
{ Show the last pushed element by modifying the stack. }
MessageDlg('Last pushed element is: "' + Stack.Pop() + '".', mtInformation, [mbOK], 0);
{ Clear the stack. }
Stack.Clear();
{ Destroy the stack completely. }
Stack.Free;
end;
procedure TForm3.StackChanged(Sender: TObject; const Item: String; Action: TCollectionNotification);
begin
{ The Stack calls this method every time a change occurs. }
if Action = cnAdded then
MessageDlg('Element added: ' + Item, mtInformation, [mbOK], 0)
else if Action = cnRemoved then
MessageDlg('Element removed: ' + Item, mtInformation, [mbOK], 0)
else if Action = cnExtracted then
MessageDlg('Element extracted: ' + Item, mtInformation, [mbOK], 0)
end;