cs261 data structures
play

CS261 Data Structures Linked List Implementation of the Queue - PowerPoint PPT Presentation

CS261 Data Structures Linked List Implementation of the Queue Review: Linked List Stack Time complexity of ListStack operations: Push: O(1) always List Pop: O(1) always Top: O(1) always link link link How would this compare


  1. CS261 Data Structures Linked List Implementation of the Queue

  2. Review: Linked List Stack Time complexity of ListStack operations: – Push: O(1) always List – Pop: O(1) always – Top: O(1) always link link … link How would this compare to a DynArr (a dynamic array implementation of a stack) ? – Push: O( 1+ ) average, O(n) worse, O(1) best – Pop : O(1) always – Top : O(1) always – In practice, dynamic array is slightly faster in real timings

  3. Linked List Queue • Could we use our linked list as is, to implement a queue? List firstLink (or head) link link … link

  4. Modification#1: Tail Pointer lastLink (or tail) List firstLink (or head) link link link … link Front Back Which side should we make the ‘front’ of the queue ?

  5. Modification#2: Sentinel • A sentinel is a special marker at the front and/or back of the list • Has no value and never removed • Helps us avoid special cases in the code associated with null references since it ’ s never null (e.g. first/last never point to null) • Simplifies some operations • An empty list always has a sentinel lastLink lastLink List List firstLink firstLink Link Link … next s next next next Sentinel

  6. listQueue struct struct listQueue { struct Link *firstLink;/* Always pts to Sent */ struct Link *lastLink; } lastLink List firstLink Link Link … next next next next After additions

  7. ListQueueInit void listQueueInit (struct listQueue *q) { struct link *lnk = malloc(sizeof(struct link)); assert(lnk != 0); /* lnk is the sentinel */ lnk->next = 0; q->firstLink = q->lastLink = lnk; } Initially lastLink List firstLink s next

  8. Sentinel vs. No Sentinel /* No Sentinel */ void addBackListQueue (struct listQueue *q, TYPE e) { struct Link * lnk = ... assert(lnk != 0); lnk->next = 0; Empty Case? lnk->value = e; lastLink List /* lastLink may be null!! */ if(!isEmptyListQueue(q)){ firstLink q->lastLink->next = lnk; q->lastLink = lnk; }else q->firstLink = q->lastLink = lnk; } lastLink List firstLink Link Link … next next next next

  9. addBackListQueue (Enqueue) /* Sentinel */ void addBackListQueue (struct listQueue *q, TYPE e) { struct Link * lnk = malloc (….) assert(lnk != 0); lnk->next = 0; lnk->value = e; /* we know it has a lastLink. */ q->lastLink->next = lnk; q->lastLink = lnk; } Empty Case? lastLink List firstLink s next

  10. Your Turn • Worksheet #18 – Linked List Queue Implementation

Recommend


More recommend