队列是一种基本的数据结构应用广泛
此处要求实现一个双向队列
双向队列的难点在于之前的队列是单向的,如果要在O(1)内完成insert delete操作,显然我们必须要知道某个结点的前驱后继
那么我们最简单的方式就是建立一个单元结点存储结点值以及结点的前驱后继
我们在每次插入删除中更新结点信息即可
然而问题是当我们将代码实现以后不能简单的用所得队列来进行值返回
这是因为双向队列导致了一个必然后果就是loop 因此,我们要设立一个selector print 利用O(n)来遍历所得的双向队列,输出结果
这样我们就得到了4个O(1)insert delete的操作
(define (make-deque)
(define (make-pair a)
(let ((new-pair (cons (cons a ()) ())))
(define (dispatch m)
(cond
((eq? m 'front) (front))
((eq? m 'rear) (rear))
((eq? m 'context) (content))
((eq? m 'set-front) set-front)
((eq? m 'set-rear ) set-rear )
((eq? m 'pair) (pair))))
(define (front) (cdr new-pair))
(define (rear) (cdar new-pair))
(define (pair) new-pair)
(define (content) (caar new-pair))
(define (set-front item) (set-cdr! new-pair item))
(define (set-rear item) (set-cdr! (car new-pair) item))
dispatch))
(let ((queue (cons ()())))
(define (dispatch m)
(cond
((eq? m 'rear-insert) rear-insert)
((eq? m 'rear-delete) (rear-delete))
((eq? m 'front-insert) front-insert)
((eq? m 'front-delete) (front-delete))
((eq? m 'front-point) (front-point))
((eq? m 'rear-point ) (rear-point))
((eq? m 'print) (print))
(else (error "Error Operation --QUEUE" queue))))
(define (print)
(define (iter item)
(cond ((null? item) ())
(else (cons (caar item) (iter (cdar item))))))
(let ((pq (iter (front-point))))
(if (empty?)
()
pq)))
(define (empty?) (null? (front-point)))
(define (front-point) (car queue))
(define (rear-point ) (cdr queue))
(define (set-rear-point item) (set-cdr! queue item))
(define (set-front-point item) (set-car! queue item))
(define (rear-insert a)
(let ((new-pair (make-pair a)))
(cond
((empty?)
(set-front-point (new-pair 'pair))
(set-rear-point (new-pair 'pair)))
(else
((new-pair 'set-front) (rear-point))
(set-cdr! (car (rear-point)) (new-pair 'pair))
(set-rear-point (new-pair 'pair))))))
(define (rear-delete)
(let ((last-pair (cdr (rear-point))))
(cond
((empty?)
(error "Empty Queue" queue))
(else
(set-cdr! (car last-pair) ())
(set-rear-point last-pair)))))
(define (front-insert a)
(let ((new-pair (make-pair a)))
(cond
((empty?)
(set-front-point (new-pair 'pair))
(set-rear-point (new-pair 'pair)))
(else
((new-pair 'set-rear) (front-point))
(set-cdr! (front-point) (new-pair 'pair))
(set-front-point (new-pair 'pair))))))
(define (front-delete)
(let ((last-pair (cdar (front-point))))
(cond
((empty?)
(error "Empty Queue" queue))
(else
(set-cdr! last-pair ())
(set-front-point last-pair)))))
dispatch))
然后,说一下不足,首先对于内部的compound data pair的设计封装比较失败,dispatch作用不大
其次就是deque的front-point 以及rear-point 无法作为返回值,否则将造成栈溢出(loop)