栈的指针实现

来源:互联网 发布:子曰诲女知之乎的拼音 编辑:程序博客网 时间:2024/04/29 03:35

在算法中要用到多个栈时,最好用链表作为栈的存储结构,即用指针来实现栈。用这种方式实现的栈也称为链栈,见图4。由于栈的插人和删除操作只在表头进行,因此用指针实现栈时没有必要像单链表那样设置一个表头单元。

图4 链栈

栈的类型说明与单链表类似。

type

 TNode=record

    element:TElement;

        next:^TNpde;

       ent;

 TStack=^TNode

链栈的基本操作实现如下:

procedure MakeNull(Var S:TStack);

var p:TStack;

begin

 p:=S;

 while S<>nil do

  begin

   S:=S^.next;

   dispose(p); {释放该单元占用的内存空间}

   p:=S;

  end;

end;

function Empty(var S:Stack):Boolean;

begin

 return(S=nil);

end;

finction Top(var S:TStack):TElement;

begin

 if Empty(S) then Error('The stack is empty.')

             else return(S.element);

end;

procedure Pop(var S:TStack);

var p:TStack;

begin

 if Empty(S) then Error('The stack is empty.')

             else begin

                   p:=S;

                   S:=S^.next;

                   dispose(p);

                  end;

end;

procedure Push(x:TElement;var S:TStack);

var p:TStack;

begin

 new(p);

 p^.element:=x;

 p^.next:=S;

 S:=p;

end;

显然,以上操作中只用MakeNull的复杂性为O(n),其余的复杂性为O(1)。