Skip to content

Instantly share code, notes, and snippets.

@habib-sadullaev
Last active February 22, 2019 10:31
Show Gist options
  • Save habib-sadullaev/d6db3480c95fb77939c6caffb600409a to your computer and use it in GitHub Desktop.
Save habib-sadullaev/d6db3480c95fb77939c6caffb600409a to your computer and use it in GitHub Desktop.
sicp deque implementation
#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)))
@habib-sadullaev
Copy link
Author

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 predicate empty-deque?, selectors front-deque and rear-deque, mutators front-insert-deque!, rear-insert-deque!, front-delete-deque!, and rear-delete-deque!. Show how to represent deques using pairs, and
give 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment