用vbscript的链栈实现LIFO的方法。节点和栈类主体如下:
Option Explicit
'-----------------------------------------
' 链表栈 by.Shine
'-----------------------------------------
Class StackNode '定义节点类
Private Data '数据域
Private NextP '指针域
Public Property Let letData(da) '数据域set方法
Data=da
End Property
Public Property Get getData '数据域get方法
getData=Data
End Property
Public Property Set setNextP(obj) '指针域set方法
Set NextP=obj
End Property
Public Property Get getNextP '指针域get方法
Set getNextP=NextP
End Property
End Class
Class Stack '定义栈体类
Private Top '栈顶
Private count '栈元素数目
Private Sub Class_Initialize '构造方法初始化
count=0
Set Top=New StackNode
Set Top.setNextP=Nothing
End Sub
Public Sub Push(elem) '压栈,链栈理论上不会溢出
If IsEmpty(Top.getData)=True Then
Top.letData=elem
count=count+1
Else
Dim ndobj
Set ndobj=New StackNode
Set ndobj.setNextP=Top.getNextP
ndobj.letData=Top.getData
Top.letData=elem
Set Top.setNextP=ndobj
count=count+1
End If
End Sub
Public Function Pop '弹栈
If IsRaw=True Then '检查栈空
MsgBox "Stack is empty"
Exit Function
Else
If count >1 Then
Pop=Top.getData
Top.letData=Top.getNextP.getData
Set Top.setNextP=Top.getNextP.getNextP
Else
Pop=Top.getData
Top.letData=Empty
End If
count=count-1
End If
End Function
Public Function GetTop '取得栈顶元素
If IsRaw=True Then
MsgBox "Stack is empty"
Exit Function
Else
GetTop=Top.getData
End If
End Function
Public Function IsRaw '判断栈是否空栈
If count > 0 Then
IsRaw=False
Else
IsRaw=True
End If
End Function
Public Function StackLength '取得栈内元素长
StackLength=count
End Function
Public Sub Clear '清空栈
count=0
Top.letData=Empty
End Sub
End Class
实例对像的测试代码:
'-------------------------------
' 脚本空间调用类实例
'-------------------------------
Dim TestST,i,str '定义变量
Set TestST=New Stack '实例对象
MsgBox TestST.IsRaw '测试是否为空栈
MsgBox TestST.StackLength '取得栈表长
TestST.Push "TESTTING" '测试压栈
TestST.Clear '测试清空栈表
TestST.Push "U" '测试连续压栈
TestST.Push "O"
TestST.Push "Y"
TestST.Push "E"
TestST.Push "V"
TestST.Push "O"
TestST.Push "L"
TestST.Push "I"
MsgBox TestST.GetTop '取得当前栈顶元素
MsgBox TestST.IsRaw '测试是否为空栈
MsgBox TestST.StackLength '取得栈表长
str=""
For i=1 To TestST.StackLength Step 1
str=str&TestST.Pop&" " '测试连续弹栈并暂存
Next
MsgBox str '打印弹栈内容,反序显示
MsgBox TestST.IsRaw '测试是否为空栈
MsgBox TestST.StackLength '取得栈表长
本文详细介绍了使用VBScript语言通过链表实现栈的后进先出(LIFO)操作,包括节点类和栈类的定义与实现。提供了实例对象测试代码,演示了压栈、弹栈、获取栈顶元素、判断栈是否为空等基本功能。
114

被折叠的 条评论
为什么被折叠?



