Last active
February 22, 2019 10:31
-
-
Save habib-sadullaev/d6db3480c95fb77939c6caffb600409a to your computer and use it in GitHub Desktop.
sicp deque implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(define (make-deque) (mcons null null)) | |
(define (front deque) (mcar deque)) | |
(define (rear deque) (mcdr deque)) | |
(define (set-front! deque item) (set-mcar! deque item)) | |
(define (set-rear! deque item) (set-mcdr! deque item)) | |
(define (empty? deque) (null? (front deque))) | |
(define (print deque) | |
(define (collect deque result) | |
(if (null? deque) | |
result | |
(collect (mcdr deque) | |
(cons (mcar (mcar deque)) result)))) | |
(collect (rear deque) null)) | |
(define (insert-front! deque item) | |
(let ([new-pair (mcons (mcons item null) null)]) | |
(cond ((empty? deque) | |
(set-front! deque new-pair) | |
(set-rear! deque new-pair)) | |
(else | |
(set-mcdr! (mcar new-pair) (front deque)) | |
(set-mcdr! (front deque) new-pair) | |
(set-front! deque new-pair)))) | |
(print deque)) | |
(define (insert-rear! deque item) | |
(let ([new-pair (mcons (mcons item null) null)]) | |
(cond ((empty? deque) | |
(set-front! deque new-pair) | |
(set-rear! deque new-pair)) | |
(else | |
(set-mcdr! (mcar (rear deque)) new-pair) | |
(set-mcdr! new-pair (rear deque)) | |
(set-rear! deque new-pair)))) | |
(print deque)) | |
(define (delete-rear! deque) | |
(if (empty? deque) | |
(error 'empty) | |
(begin | |
(set-mcdr! (mcar (mcdr (rear deque))) null) | |
(set-rear! deque (mcdr (rear deque))) | |
(print deque)))) | |
(define (delete-front! deque) | |
(if (empty? deque) | |
(error 'empty) | |
(begin | |
(set-mcdr! (mcdr (mcar (front deque))) null) | |
(set-front! deque (mcdr (mcar (front deque)))) | |
(print deque))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exercise 3.23: A deque (“double-ended queue”) is a sequence in which items can be inserted and deleted at either the front or the rear. Operations on deques are the constructor
make-deque
, the predicateempty-deque?
, selectorsfront-deque
andrear-deque
, mutatorsfront-insert-deque!
,rear-insert-deque!
,front-delete-deque!
, andrear-delete-deque!
. Show how to represent deques using pairs, andgive implementations of the operations.* All operations should be accomplished in Θ(1) steps.
* Be careful not to make the interpreter try to print a structure that contains cycles.