1

因为 Squeak 是一个开源环境,我们可以看到如下数据结构的实现OrderedCollection>>addFirst

addFirst: newObject 
"Add newObject to the beginning of the receiver. Answer newObject."

firstIndex = 1 ifTrue: [self makeRoomAtFirst].
firstIndex := firstIndex - 1.
array at: firstIndex put: newObject.
^ newObject

OrderedCollection>>removeFirst

removeFirst: n
"Remove first n object into an array"

| list |
list := Array new: n.
1 to: n do: [:i |
    list at: i put: self removeFirst].
^ list

然后我可以操作堆栈数据结构,对吗?

我被告知 Smalltalk 没有指针结构;尽管像 Java 这样的语言也没有指针结构,而不是脚本语言,但它应该实现一些基本的数据结构,如树、图(由Scripting: Higher Level Programming for the 21st Century引用),然后提出进一步的问题:

Smalltalk 是如何实现树形数据结构的?

4

1 回答 1

4

Smalltalk 到处都有指针,就像 Java 一样。你不能做类似 C 的事情,比如递增指针,但这myVar := OrderedCollection new意味着它myVar是一个指向空的指针OrderedCollection

是的,您可以使用 OrderedCollection 模拟堆栈,方法是使用addFirst:推送元素和removeFirst:弹出removeFirst元素。addFirst:(类似地,您可以通过使用 推送元素和使用 移除它们来模拟队列removeLast

您可以像使用任何语言一样在 Smalltalk 中实现树。例如,我编写了一个非常基本的树实现来玩zippers。看看 class ZTree,它实现了一个非常通用的树结构——一个节点可以有任意数量的子节点。

于 2011-02-22T08:42:05.800 回答