Skip to content

Commit 756dcf4

Browse files
committed
Add solution for exercise3-18
1 parent 6f0450c commit 756dcf4

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

chapter3/exercise3-19.rkt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#lang racket
2+
;;; 支持 mutable 与 immutable
3+
;;; 双指针方案
4+
;;; 时间复杂度 O(N), 空间复杂度 O(1)
5+
;;; (这是非常经典的判断链表是否有环的做法,需要一种很聪明的想法原来只
6+
;;; 能算是 Leetcode的 Medium)
7+
(define (has-circle? x)
8+
(define (safe-cdr lst)
9+
(cond ((pair? lst)
10+
(cdr lst))
11+
((mpair? lst)
12+
(mcdr lst))
13+
(else '())))
14+
15+
(define (is-pair? lst)
16+
(or (pair? lst) (mpair? lst)))
17+
18+
(let loop ((tortoise x)
19+
(hare (safe-cdr x)))
20+
(cond ((or (not (is-pair? tortoise))
21+
(not (is-pair? hare))
22+
(not (is-pair? (safe-cdr hare))))
23+
#f)
24+
((eq? tortoise hare)
25+
#t)
26+
(else
27+
(loop (safe-cdr tortoise)
28+
(safe-cdr (safe-cdr hare))))
29+
))
30+
)
31+
32+
(module+ test
33+
(require rackunit)
34+
(test-case "Test for circular? with circular mutable list"
35+
(define cycle (mcons 1 (mcons 2 null)))
36+
(set-mcdr! (mcdr cycle) cycle)
37+
(check-true (has-circle? cycle)))
38+
(test-case "Test for circular? with non-circular mutable list"
39+
(define non-cycle (mcons 1 (mcons 2 null)))
40+
(check-false (has-circle? non-cycle)))
41+
42+
(test-case "Test for circular? with immutable list"
43+
(define imm-list (list 1 2 3))
44+
(check-false (has-circle? imm-list)))
45+
)

0 commit comments

Comments
 (0)