File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ )
You can’t perform that action at this time.
0 commit comments