110 likes | 210 Views
CS261 Data Structures. Linked List Implementation of the Deque. Deque Interface (Review). int isEmpty(); void addFront(TYPE val); // Add value at front of deque. void addBack (TYPE val); // Add value at back of deque.
E N D
CS261 Data Structures Linked List Implementation of the Deque
Deque Interface (Review) int isEmpty(); void addFront(TYPE val); // Add value at front of deque. void addBack (TYPE val); // Add value at back of deque. void removeFront(); // Remove value at front. void removeBack (); // Remove value at back. TYPE front(); // Get value at front of deque. TYPE back(); // Get value at back of deque.
Linked List Deque • What if we want to add and remove elements from both front and back? tail List head link link link tail head val val … val links links links
Modification #3: Double Links prev • Point forward to the next element • Point backwards to the previous element structDLink { TYPE val; structDLink *next; /* Link to prevnode. */ structDLink *prev; /* Link to next node. */ }; Link next lastLink List firstLink prev prev prev prev … Link Link Link next next next next
linkedListDequeStruct structlinkedList { intsize; structdlink * frontSentinel; structdlink * backSentinel; };
linkedListDequeInit void LinkedListInit (structlinkedList *q) { q->frontSentinel = malloc(sizeof(structdlink)); assert(q->frontSentinel != 0); q->backSentinel = malloc(sizeof(structdlink)); assert(q->backSentinel); q->frontSentinel->next = q->backSentinel; q->backSentinel->prev = q->frontSentinal; q->size = 0; } backSent List frontSent prev next Sentinel Sentinel
Advantage of Sentinels • Consider a deque, with two sentinels: • Pointer to front sentinel: frontSent • Pointer to back sentinel: backSent • Add to front and add to back are now special cases of more general “add before” operation This is similar to most standard library Deque implementations (Java LinkedList) AddBefore(nodeB, X) A A B X B
Advantage of Sentinels • Consider a deque, with two sentinels: • Pointer to front sentinel: frontSent • Pointer to back sentinel: backSent • Add to front and add to back are now special cases of more general “add before” operation This is similar to most standard library Deque implementations (Java LinkedList) backSent List frontSent prev prev prev prev … Link Link next next next next
Adding to the LL Deque void addBackListDeque(structListDeque *q,TYPEval) { _addBefore(q->backSent, val); } void addFrontListDeque(structListDeque *q,TYPEval) { _addBefore(q->frontSent->next, val); } backSent List frontSent prev prev prev prev prev … Link Link next next next next next
Removing from the LL Deque void removeFirstListDeque(structListDeque*q) { assert(!isEmptyListDeque(q)); _removeLink(q->frontSent->next); } void removeLastListDeque(structListDeque*q) { assert(!isEmptyListDeque(q)); _removeLink (q->backSent->prev); } backSent List frontSent prev prev prev prev prev … Link Link next next next next next
Your Turn… Worksheet #19: _addBefore, _removeLink