99道lisp练习题----(一)列表操作

本文分享了99道源于http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html的Lisp编程练习,涵盖了各种列表操作,旨在提升Lisp编程技巧。网站上提供了详细的解题答案,供学习者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

99道习题来自 http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html,并且该网页上有解答。

P01 (*) Find the last box of a list. (查找列表最后一个元素)
Example:
* (my-last '(a b c d))
(D)
(defun my-last (lst)
  (if (null (cdr lst)) ;(cdr nil) equal nil
      lst
      (my-last (cdr lst))))
(defun my-last-1 (lst)
  (if (null lst)
      nil
      (let ((len (length lst)))
	(nthcdr (- len 1) lst))))
P02 (*) Find the last but one box of a list.(除最后一个元素外的列表)
Example:
* (my-but-last '(a b c d))
(C D)
(defun my-but-last (lst)
  (let ((len (length lst)))
    (if (> len 1)
	(subseq lst (- (length lst) 2))
	nil)))
(defun my-but-last-1 (lst)
  (if (null (cddr lst))
      lst
      (my-but-last-1 (cdr lst))))
网页上有新的解法

P03 (*) Find the K'th element of a list. (查找列表的第K个元素)
The first element in the list is number 1.
Example:
* (element-at '(a b c d e) 3)
C
(defun element-at (lst n)
  (cond ((null lst) nil)
	((= n 1) (car lst))
	(t (element-at (cdr lst) (- n 1)))))
P04 (*) Find the number of elements of a list.

(defun lenght-lst (lst)
  (if (null lst)
      0
      (1+ (lenght-lst (cdr lst)))))
P05 (*) Reverse a list.

(defun reverse-lst (lst)
  (if (null lst)
      nil
      (nconc (reverse-lst (cdr lst)) (list (car lst)))))
(defun reverse-lst-1 (lst)
  (labels ((rec (lst acc)
	     (if (null lst)
		 acc
		 (rec (cdr lst) (cons (car lst) acc)))))
    (rec lst nil)))

P06 (*) Find out whether a list is a palindrome. 

链表是否中心对称,将链表逆转,然后查看链表是否一样

A palindrome can be read forward or backward; e.g. (x a m a x).
(defun palindrome (lst)
  (let ((lst1 (reverse-lst-1 lst)))
    (labels ((rec (lst lst1)
	       (if (null lst)
		   t
		   (and (equal (car lst) (car lst1))
			(rec (cdr lst) (cdr lst1))))))
      (rec lst lst1))))
(defun palindrome-1 (lst)
  (let ((lst1 (reverse-lst-1 lst)))
    (equal lst lst1)))
P07 (**) Flatten a nested list structure.
Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).

Example:
* (my-flatten '(a (b (c d) e)))

(A B C D E)


(defun my-flatten (tree)
  (cond ((null tree) nil)
	((atom tree) (list tree))
	(t (nconc (my-flatten (car tree))
		  (my-flatten (cdr tree))))))

P08 (**) Eliminate consecutive duplicates of list elements.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值