1 / 64

CS201: Data Structures and Discrete Mathematics I

CS201: Data Structures and Discrete Mathematics I. Linked Lists, Stacks and Queues. Data Structure. A construct that can be defined within a programming language to store a collection of data one may store some data in an array of integers, an array of objects, or an array of arrays.

Download Presentation

CS201: Data Structures and Discrete Mathematics I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS201: Data Structures and Discrete Mathematics I Linked Lists, Stacks and Queues

  2. Data Structure • A construct that can be defined within a programming language to store a collection of data • one may store some data in an array of integers, an array of objects, or an array of arrays CS 201

  3. Abstract Data Type (ADT) • Definition: a collection of data together with a set of operations on that data • specifications indicate what ADT operations do, but not how to implement them • data structures are part of an ADT’s implementation • Programmer can use an ADT without knowing its implementation. CS 201

  4. Typical Operations on Data • Add data to a data collection • Remove data from a data collection • Ask questions about the data in a data collection. E.g., what is the value at a particular location, and is x in the collection? CS 201

  5. Why ADT • Hide the unnecessary details • Help manage software complexity • Easier software maintenance • Functionalities are less likely to change • Localised rather than global changes CS 201

  6. Illustration CS 201

  7. Linked Lists

  8. Lists • List: a finite sequence of data items a1, a2, a3, …, an • Lists are pervasive in computing • e.g. class list, list of chars, list of events • Typical operations: • Creation • Insert / remove an element • Test for emptiness • Find an item/element • Current element / next / previous • Find k-th element • Print the entire list CS 201

  9. listArray cur curSize n unused a2 a3 an a1 0 1 2 n-1 m Array-Based List Implementation • One simple implementation is to use arrays • A sequence of n-elements • Maximum size is anticipated a priori. • Internal variables: • Maximum size maxSize (m) • Current size curSize (n) • Current index cur • Array of elements listArray CS 201

  10. Example : insert(2, it, arr) arr Size 8 a1 a2 a3 a7 a4 a5 a6 a8 Step 1 : Shift upwards Step 2 : Write into gap 9 a1 a2 a7 a4 a5 a3 a6 a8 Size arr Step 3 : Update Size it 8 Inserting Into an Array • While retrieval is very fast, insertion and deletion are very slow • Insert has to shift upwards to create gap CS 201

  11. Coding typedef struct { int arr[MAX]; int max; int size; } LIST void insert(int j, int it, LIST *pl) { // pre : 1<=j<=size+1 int i; for (i=pl->size; i>=j; i=i-1) // Step 1: Create gap { pl->arr[i+1]= pl->arr[i]; }; pl->arr[j]= it; // Step 2: Write to gap pl->size = pl->size + 1; // Step 3: Update size } CS 201

  12. Example: deleteItem(4, arr) size arr 9 a1 a2 it a7 a4 a5 a3 a6 a8 Step 1 : Close Gap 8 size arr Step 2 : Update Size a8 9 a8 a7 a1 a2 a5 it a6 a3 Not part of list Deleting from an Array • Delete has to shift downwards to close gap of deleted item CS 201

  13. Coding void delete(int j, LIST *pl) { // pre : 1<=j<=size for (i=j+1; i<=pl->size; i=i+1) // Step1: Close gap { pl->arr[i-i]=pl->arr[i]; }; // Step 2: Update size pl->size = pl->size - 1; } CS 201

  14. head represents null item next ai a1 a2 a3 a4 Linked List Approach • Main problem of array is the slow deletion/insertion since it has to shift items in its contiguous memory • Solution: linked list where items need not be contiguous with nodes of the form • Sequence (list) of four items < a1,a2,a3,a4 > can be represented by: CS 201

  15. Pointer-Based Linked Lists • A node in a linked list is usually a struct struct Node { int item Node *next; }; //end struct • A node is dynamically allocated Node *p; p = malloc(sizeof(Node)); A node CS 201

  16. Pointer-Based Linked Lists • The head pointer points to the first node in a linked list • If head is NULL, the linked list is empty • head=NULL • head=malloc(sizeof(Node)) CS 201

  17. A Sample Linked List CS 201

  18. Traverse a Linked List • Reference a node member with the -> operator p->item; • A traverse operation visits each node in the linked list • A pointer variable cur keeps track of the current node for (Node *cur = head; cur != NULL; cur = cur->next) x = cur->item; CS 201

  19. Traverse a Linked List The effect of the assignment cur = cur->next CS 201

  20. Delete a Node from a Linked List • Deleting an interior/last node prev->next=cur->next; • Deleting the first node head=head->next; • Return deleted node to system cur->next = NULL; free(cur); cur=NULL; CS 201

  21. Delete a Node from a Linked List Deleting a node from a linked list Deleting the first node CS 201

  22. Insert a Node into a Linked List • To insert a node between two nodes newPtr->next = cur; prev->next = newPtr; Inserting a new node into a linked list CS 201

  23. Insert a Node into a Linked List • To insert a node at the beginning of a linked list newPtr->next = head; head = newPtr; Inserting at the beginning of a linked list CS 201

  24. Insert a Node into a Linked List • Inserting at the end of a linked list is not a special case if cur is NULL newPtr->next = cur; prev->next = newPtr; Inserting at the end of a linked list CS 201

  25. Look up BOOLEAN lookup (int x, Node *L) { if (L == NULL) return FALSE else if (x == L->item) return TRUE else return lookup(x, L-next); } CS 201

  26. Functions isEmpty getLength insert delete Lookup … Data Members head Size Local variables to member functions cur prev An ADT Interface for List CS 201

  27. forward traversal Doubly Linked List. next head x1 x4 x2 x3 prev backward traversal Doubly Liked Lists • Frequently, we need to traverse a sequence in BOTH directions efficiently • Solution : Use doubly-linked list where each node has two pointers CS 201

  28. Circular Linked List. head . . . x1 x2 xn Circular Linked Lists • May need to cycle through a list repeatedly, e.g. round robin system for a shared resource • Solution : Have the last node point to the first node CS 201

  29. Stacks

  30. pop 6 7 2 3 What is a Stack? • A stack is a list with the restriction that insertions and deletions can be performed in only one position, namely, the end of the list, called the top. • The operations: push (insert) and pop (delete) push(o) Top CS 201

  31. Stack ADT Interface • The main functions in the Stack ADT are (S is the stack) boolean isEmpty(); // return true if empty boolean isFull(S); // return true if full void push(S, item); // insert item into stack void pop(S); // remove most recent item void clear(S); // remove all items from stack Item top(S); // retrieve most recent item Item topAndPop(S); // return & remove most recent item CS 201

  32. s top d e a b c Sample Operation Stack S = malloc(sizeof(stack)); push(S, “a”); push(S, “b”); push(S, “c”); d=top(S); pop(S); push(S, “e”); pop(S); CS 201

  33. StackLL lst Top of Stack = Front of Linked-List LinkedListItr Implementation by Linked Lists • Can use a Linked List as implementation of stack head a1 a2 a3 a4 CS 201

  34. Code struct Node { int element; Node * next; }; typedef struct Node * STACK; CS 201

  35. More code CS 201

  36. More Code CS 201

  37. StackAr arr 0 1 7 8 9 3 6 4 5 2 D C A B top Implementation by Array • use Array with a top index pointer as an implementation of stack E F A CS 201

  38. Code CS 201

  39. More code CS 201

  40. More code CS 201

  41. Effects CS 201

  42. Applications • Many application areas use stacks: • line editing • bracket matching • postfix calculation • function call stack CS 201

  43. Input : Corrected Input : Reversed Output : abc_defgh2klpqrwxyz abc_defg2klpwxyz zyxwplk2gfed_cba Line Editing • A line editor would place characters read into a buffer but may use a backspace symbol (denoted by ) to do error correction • Refined Task • read in a line • correct the errors via backspace • print the corrected line in reverse CS 201

  44. Stack The Procedure • Initialize a new stack • For each character read: • if it is a backspace, pop out last char entered • if not a backspace, push the char into stack • To print in reverse, pop out each char for output r z h Input : fghryz Corrected Input : Reversed Output : g y fyz f zyf CS 201

  45. Bracket Matching Problem • Ensures that pairs of brackets are properly matched • An Example:{a,(b+f[4])*3,d+f[5]} • Bad Examples: (..)..) // too many closing brackets (..(..) // too many open brackets [..(..]..) // mismatched brackets CS 201

  46. Stack Informal Procedure Initialize the stack to empty For every char read if open bracket then push onto stack if close bracket, then return & remove most recent item from the stack if doesn’t match then flag error if non-bracket, skip the char read [ ] Example {a,(b+f[4])*3,d+f[5]} [ ] ( ) { } CS 201

  47. postfix 2 3 * 4 + (2*3)+4 infix 2*3+4 2 3 4 + * 2*(3+4) Postfix Calculator • Computation of arithmetic expressions can be efficiently carried out in Postfix notation with the help of a stack. Infix - arg1 op arg2 Prefix - op arg1 arg2 Postfix - arg1 arg2 op CS 201

  48. Expr 2 3 4 + * Stack Informal Procedure Initialise stack S For each item read. If it is an operand, push on the stack If it is an operator, pop arguments from stack; perform operation; push result onto the stack push(S, 2) push(S, 3) push(S, 4) arg2=topAndPop(S) arg1=topAndPop(S) push(S, arg1+arg2) 4 3+4=7 3 arg2=topAndPop(S) arg1=topAndPop(S) push(S, arg1*arg2) 2*7=14 2 CS 201

  49. Summary • The ADT stack operations have a last-in, first-out (LIFO) behavior • Stack has many applications • algorithms that operate on algebraic expressions • a strong relationship between recursion and stacks exists • Stack can be implemented using arrays or linked lists CS 201

  50. Queues

More Related