在二叉树中插入节点时异常堆栈溢出

时间:2015-10-01 10:46:28

标签: common-lisp binary-tree stack-overflow clisp

CLISP版本:2.49

叶节点

[
                        [ {"name" : "Chennai super kings", "score" : 10 }, {"name" : "spartans",  "score" : 5} ],
                        [ {"name" : "Lions11", "score" : 15 }, {"name" : "Kings Xl Punjab",  "score" : 10} ],
                        [ {"name" : "Zimbabwe", "score" : 15 }, {"name" : "Red Steel",  "score" : 5} ],
                    ], 
                    [
                        [ {"name" : "Chennai super kings", "score" : 10 }, {"name" : "Zimbabwe",  "score" : 5} ],
                    ],
                    [
                        [ {"name" : "Chennai super kings", "score" : 10 }, {"name" : "Lions11",  "score" : 5} ],
                    ]

非叶​​节点

(value (NIL) (NIL))

代码(仅用于调试的“格式”)

(value (value (NIL) (NIL)) (NIL))

测试

; (nil) means NULL
(defun binary-insert (root obj <) 
(if (null (cdr root))
    (progn 
        (format t "In Null [~A] => " root) 
        (setf (car root) obj) 
        (format t "mid [~A] => " root) 
        (setf (cdr root) '((nil) (nil))) 
        (format t "[~A]~%" root))
    (if (funcall < obj (car root))
        (progn 
            (format t "In Left [~A] => " root) 
            (binary-insert (nth 1 root) obj <) 
            (format t "[~A]~%" root)) ; Left
        (progn 
            (format t "In Right [~A] => " root) 
            (binary-insert (nth 2 root) obj <) 
            (format t "[~A]~%" root)) ; Right
        )
    )
)

该程序似乎在执行

后死亡
[1]> (load "binary_tree.lisp")
;; Loading file binary_tree.lisp ...
;; Loaded file binary_tree.lisp
T
[2]> (setf *glb-rt* '(NIL))
(NIL)
[3]> (binary-insert *glb-rt* 10 #'<)
In Null [(NIL)] => mid [(10)] => [(10 (NIL) (NIL))]
NIL
[4]> *glb-rt*
(10 (NIL) (NIL))
[5]> (binary-insert *glb-rt* 5 #'<)
In Left [(10 (NIL) (NIL))] => In Null [(NIL)] => mid [(5)] => [
*** - Lisp stack overflow. RESET

...谢谢

[更新]

之前(setf(cdr root)'((NIL)(NIL))),“root”是(5)

另一项测试

(setf (cdr root) '((NIL) (NIL)))

1 个答案:

答案 0 :(得分:1)

CLISP常见问题How do I avoid stack overflow?

已回答了这个问题

在你的情况下,第一个建议有效:在

之后
(setq *print-circle* t)

我们得到了

In Left [(10 (NIL) (NIL))] => In Null [(NIL)] => mid [(5)] => [#1=(5 #1#  (NIL))]

即你错误地创造了一个圆形结构。

PS。你现在欠我10 zorkmids: - )