Gth*_*ma2 2 smalltalk pass-by-reference binary-heap
所以我正在开发一个程序,该程序应该"堆积"用户添加到集合中的整数等等.但是,当我尝试访问作为参数传递给函数的Node的左子节点时,我现在遇到了问题.Visual Works耗尽内存......
奇怪的是,在调试器中,我可以看到传递节点的Left子节点已创建并正确分配给传递的节点.但是当我尝试通过源代码访问它时,我得到一个疯狂的内存错误.
这是相应的代码.希望它是可读的
一旦被调用,就会发生错误的函数:
addLeftChildTo: aNode
"Determine Left child of passed node. Set that child's parent node as self. Imprint the index where that value was retrieved from the array."
| temp leftChildIndex |
2 * aNode indexOfNode <= arrayOfInput size
ifTrue:
[leftChildIndex := 2 * aNode indexOfNode.
aNode left: (arrayOfInput at: leftChildIndex).
aNode left parentNode: aNode. <---VW Runs out of memory and crashes here. This occurs once the debugger dives into the 'left' accessor method of the passed aNode object.
aNode left indexOfNode: leftChildIndex.
self bubbleUp: aNode left.
self bubbleUpArrayOfInput: aNode left]
ifFalse: [aNode left: nil]
Run Code Online (Sandbox Code Playgroud)
以下是BinaryHeapNode类的"left"访问器方法
left
^self left
left: aValue
left := BinaryHeapNode new: aValue.
Run Code Online (Sandbox Code Playgroud)
如果看到最初调用addLeftChildTo:方法的代码很有帮助...
populateHeap
"from passed array of input"
"Add a node (typically a node with an element from the ArrayOfInput) to the heap. Bubble up as you go."
| temp |
rootNode isNil
ifTrue:
[rootNode := BinaryHeapNode new: (arrayOfInput at: 1).
rootNode indexOfNode: indexOfArray.
self addLeftChildTo: rootNode. <--- Call to function with problematic code.
...
Run Code Online (Sandbox Code Playgroud)
我不明白我做错了什么,我已经坚持了几个小时这个问题.有任何想法吗?
你使用访问者#left进行了无限递归:
left
^self left
Run Code Online (Sandbox Code Playgroud)
这种方法实际上是自称.只返回实例变量^left.