在Lisp中合并列表

时间:2015-10-29 04:53:19

标签: recursion lisp common-lisp

我正在尝试获取表示二叉搜索树的列表并按顺序输出列表元素(displayBST '(10(5(3(2()())())())())) - > (2 3 5 10)。所有我似乎都可以得到的列表看起来像(((2 3) 5) 10),我不知道如何制作所有数字基本元素。

(let((SUMS))
(defun displayBST(elements)
 ;IF NO ELEMENTS return SUMS

 (cond((null elements)
           nil)
      ;if both branches null return first element
      ((and(null (second elements))(null (third elements)))
            (print (first elements))
            (first elements))
      ;if left branch not null
      ((not(null (second elements)))
            ;if right branch null
            (cond((null (third elements))
                      ;set SUMS to (left branch) and first element
                      (setf SUMS (list (displayBST(second elements)) (first elements))))
                   ;else set SUMS to (left branch) and first element and (right branch)
                  (t(SETF sums (append (displayBST(second elements))(first elements)(displayBST(third elements)))))))
      ;if left branch null and right not null
      ((not (null(third elements)))
           ;set SUMS to first element and (right branch)
           (setf SUMS (list (first elements) (displayBST(third elements))))))))

1 个答案:

答案 0 :(得分:0)

考虑如何将给定元素连接到函数递归返回的值。如果你想要X + Y =(X Y)你应该使用(cons X(列表Y))。因此,基本情况(即(null(第二元素))和(null(第三元素))应该返回(列表(第一元素))。 你想要的是这样的:

(let((SUMS))
(defun displayBST(elements)
 ;IF NO ELEMENTS return SUMS

 (cond((null elements)
           nil)
      ;if both branches null return first element
      ((and(null (second elements))(null (third elements)))
            (print (first elements))
            (list (first elements)))
      ;if left branch not null
      ((not(null (second elements)))
            ;if right branch null
            (cond((null (third elements))
                      ;set SUMS to (left branch) and first element
                      (setf SUMS (append (displayBST(second elements)) (list (first elements)))))
                   ;else set SUMS to (left branch) and first element and (right branch)
                  (t(SETF sums (append (displayBST(second elements))(first elements)(displayBST(third elements)))))))
      ;if left branch null and right not null
      ((not (null(third elements)))
           ;set SUMS to first element and (right branch)
           (setf SUMS (cons (first elements) (displayBST(third elements))))))))