1 / 40

Department of Computer and Information Science, School of Science, IUPUI

Department of Computer and Information Science, School of Science, IUPUI. CSCI 240. Elementary Data Structures. Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu. Elementary Data Structures.

jacke
Télécharger la présentation

Department of Computer and Information Science, School of Science, IUPUI

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. Department of Computer and Information Science,School of Science, IUPUI CSCI 240 Elementary Data Structures Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu

  2. Elementary Data Structures Elementary Data Structure are fundamental approaches to organizing data. These are the building blocks that will be used to implement more complex Abstract Data Types. • Scalar (built-in) data types • Arrays • Linked Lists • Strings

  3. Scalar built-in data types • Basic building blocks for other structures: • Integers (int) • Floating-point numbers (float) • Characters (char) • Implicit type conversion allow these data types to be mixed in an expression. • Sometimes casting is required to for an expression to evaluate correctly ((float) x) / N

  4. Data Structures There is a famous saying that “Algorithms + Data Structures = Programs” (Wirth) “For may applications, the choice of the proper data structure is the only major decision involving the implementation: once the choice is made, the necessary algorithms are simple.” (Sedgewick) In fact, complexity in algorithms are a warning signal that a wrong data structure choice has been made.

  5. Data Structure • Algorithms deals with the manipulation of data • Data structure deals with the organization of data Algorithms + Data Structures = Programs • Suppose we have a list of sorted data on which we have to perform the following operations: • Search for an item • delete a specified item • insert (add) a specified item Example: suppose we begin with the following list: data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 • What is a list? • A list is a data structure where data is represented linearly. A list can be implemented using arrays on a machine. • Finite sequence of items from the same data type • Stored contiguously in the memory

  6. List implementation using an Array Example: suppose we begin with the following list: data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 Now, delete item 358 from the above list Q: What is the algorithm to delete an item? Q: What is the cost of deleting an item? data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 Q: When we delete 358, what happens to that location? Now, add item 498 onto the above list Q: Where would that item go? data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 Q: What is the cost of inserting an item? Conclusion: Using a list representation of data, what is the overall efficiency of searching, adding, and deleting items? 498

  7. Deletion of an Element from a List • Algorithm: • locate the element in the list (this involves searching) • delete the element • reorganize the list and index Example: data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 Delete 358 from the above list: • Locate 358: if we use ‘linear search’, we’ll compare 358 with each element of the list starting from the location 0. • Delete 358: remove it from the list (space=10) data: 345 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 • Reorganize the list: move the remaining elements. (space=9) data: 345 490 501 513 555 561 701 724 797 ?(797) location: 0 1 2 3 4 5 6 7 8 9

  8. Insertion of an Element in List • Algorithm: • locate the position where the element in to be inserted (position may be user-specified in case of an unsorted list or may be decided by search for a sorted list) • reorganize the list and create an ‘empty’ slot • insert the element Example: (sorted list) data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 Insert 505 onto the above list: • Locate the appropriate position by performing a binary search. 505 should be stored in location 4. • Create an ‘empty’ slot data: 345 358 490 501 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 10 • Insert 505 data: 345 358 490 501 505 513 555 561 701 724 797 location: 0 1 2 3 4 5 6 7 8 9 10

  9. Array Example: Sieve of Eratosthenes #include "stdafx.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int i, *a, N; // Prompt for N cout << "Enter N: "; cin >> N; // Dynamically allocate an array on the heap a = new int[N]; // Run the Sieve for (i = 2; i < N; i++) a[i] = 1; for (i = 2; i < N; i++) if (a[i]) for (int j = i; j*i < N; j++) a[i*j] = 0; // Print output for (i = 2; i < N; i++) if (a[i]) cout << " " << i; cout << endl; return 0; }

  10. Array Example: Sieve of Eratosthenes • Note use of dynamic array allocation • How big can N be?

  11. Methods for defining a collection of objects • Array • successive items locate a fixed distance • disadvantage • data movements during insertion and deletion • waste space in storing n ordered lists of varying size • possible solution • linked list • linked lists are dynamically allocated and make extensive use of pointers

  12. #include "stdafx.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int i, *pi; float f, *pf; pi = new int; pf = new float ; *pi = 1024; *pf = (float) 3.14; cout << "an integer = " << *pi << ", a float = " << *pf << endl; delete pi; delete pf; return 0; } allocate memory return memory Using Dynamically Allocated Storage

  13. List Implementation using Linked Lists • Linked list • Linear collection of self-referential class objects, called nodes • Connected by pointer links • Accessed via a pointer to the first node of the list • Subsequent nodes are accessed via the link-pointer member of the current node • Link pointer in the last node is set to null to mark the list’s end • Use a linked list instead of an array when • You have an unpredictable number of data elements • Your you want to insert and delete quickly.

  14. 3 2 100 … 500 Data member and pointer NULL pointer (points to nothing) Self-Referential Structures • Self-referential structures • Structure that contains a pointer to a structure of the same type • Can be linked together to form useful data structures such as lists, queues, stacks and trees • Terminated with a NULL pointer (0) • Diagram of two self-referential structure objects linked together struct node { int data; struct node *nextPtr;} • nextPtr • Points to an object of type node • Referred to as a link • Ties one node to another node

  15. Linked Lists • Types of linked lists: • Singly linked list • Begins with a pointer to the first node • Terminates with a null pointer • Only traversed in one direction • Circular, singly linked • Pointer in the last node points back to the first node • Doubly linked list • Two “start pointers” – first element and last element • Each node has a forward pointer and a backward pointer • Allows traversals both forwards and backwards • Circular, doubly linked list • Forward pointer of the last node points to the first node and backward pointer of the first node points to the last node

  16. 797 797 797 358 358 358 561 561 561 501 501 501 724 724 724 345 345 345 555 555 555 490 490 490 701 701 701 513 513 513 498 498 Linked Representation of Data • In a linked representation, data is not stored in a contiguous manner. Instead, data is stored at random locations and the current datalocation provides the information regarding the location of the next data. Adding item 498 on to the linked list Q: What is the cost of adding an item? Q: how about adding 300 and 800 onto the linked list Deleting item 358 from the linked list Q: What is the cost of deleting an item? Q: What is the cost of searching for an item?

  17. 100 400 200 300 500 2 1 4 0 5 Linked List • How do we represent a linked list in the memory • we use pointers to point to the next data item. Each location has two fields: Data Field and Pointer (Link) Field. • Linked List Implementation struct node { int data; struct node *link; }; struct node my_node; Example: START Node Element Data Field Pointer (Link) Field Null Pointer 1 2 NULL 3 3 4 5

  18. Linked List Definition Sedgewick Definition 3.2 A linked list is a set of items where each item is part of a node that also contains a link to a node. There are several conventions for the link to indicate the end of the list. • a null link that points to no node (0 or NULL) • a dummy node that contains no item • a reference back to the first node, making it a circular list.

  19. bat  cat  sat  vat NULL Singly Linked List *Figure 4.1: Usual way to draw a linked list (p.139)

  20. mat  Linked List Insertion bat  cat  sat  vat NULL *Figure 4.2: Insert mat after cat (p.140)

  21. cat  sat  mat  Linked List Deletion bat  vat NULL dangling reference

  22. ptr 10  20 NULL Example: create a two-node list typedef struct list_node *list_pointer;typedef struct list_node { int data; list_pointer link; };list_pointer ptr =NULL

  23. ptr 10  20 NULL Two Node Linked List list_pointer create2( ){/* create a linked list with two nodes */ list_pointer first, second; first = (list_pointer) malloc(sizeof(list_node)); second = ( list_pointer) malloc(sizeof(list_node)); second -> link = NULL; second -> data = 20; first -> data = 10; first ->link = second; return first;}

  24. 10  ptr 20 NULL node 50  temp Inserting a node after a given node void insert(list_pointer *ptr, list_pointer node){ /* insert a new node with data = 50 into the list ptr after node */ list_pointer temp; temp = (list_pointer) malloc(sizeof(list_node)); if (IS_FULL(temp)){ fprintf(stderr, “The memory is full\n”); exit (1); } temp->data = 50; if (*ptr) { //noempty list temp->link =node ->link; node->link = temp; } else { empty list temp->link = NULL; *ptr =temp; }}

  25. 10  20 NULL 50  20 NULL 50  ptr node trail = NULL ptr (a) before deletion (b)after deletion *Figure 4.7: List after the function call Delete(&ptr,NULL.ptr);(p.145)

  26. 10  20 NULL 50  20 NULL 50  10  20 NULL 50  20 NULL 10  List Deletion Delete the first node. ptr trail node ptr (a) before deletion (b)after deletion Delete node other than the first node. ptr trail node ptr

  27. 10  20 NULL 50  20 NULL 10  10  20 NULL 50  20 NULL 50 void delete(list_pointer *ptr, list_pointer trail, list_pointer node){/* delete node from the list, trail is the preceding node ptr is the head of the list */ if (trail) trail->link = node->link; else *ptr = (*ptr) ->link; free(node);} trail node ptr node ptr

  28. Linked List Manipulation Algorithms • List Traversal • Let START be a pointer to a linked list in memory. Write an algorithm to print the contents of each node of the list • Algorithm • set PTR = START • repeat step 3 and 4 while PTR  NULL • print PTR->DATA • set PTR = PTR -> LINK • stop 10 20 30 40 1000 2000 3000 4000 10 20 30 40 50 START Data Link PTR = LINK[PTR] PTR

  29. 1000 2000 3000 4000 START PTR = LINK[PTR] PTR Search for an Item • Search for an ITEM • Let START be a pointer to a linked list in memory. Write an algorithm that finds the location LOC of the node where ITEM first appears in the list, or sets LOC=NULL if search is unsuccessful. • Algorithm • set PTR = START • repeat step 3 while PTR  NULL • if ITEM == PTR -> DATA, then • set LOC = PTR, and Exit • else • set PTR = PTR -> LINK • set LOC = NULL /*search unsuccessful */ • Stop

  30. START Node A Node B 1000 2000 3000 4000 5000 START Node A Node B 1000 2000 3000 4000 5000 3500 Node N PTR Insert an Item • Insertion into a Listed List • Let START be a pointer to a linked list in memory with successive nodes A and B. Write an algorithm to insert node N between nodes A and B. • Algorithm • Set PTR = START • Repeat step 3 while PTR  NULL • If PTR == A, then • Set N->LINK = PTR -> LINK (or = B) • Set PTR->LINK = N • exit • else • Set PTR=PTR->LINK • If PTR == NULL insertion unsuccessful • Stop 3 cases: first node, last node, in-between node. (ex: if ITEM = 500? if ITEM = 6000?)

  31. Delete an Item • Deletion from a Linked List • Let START be a pointer to a linked list in memory that contains integer data. Write an algorithm to delete note which contains ITEM. • Algorithm • Set PTR=START and TEMP = START • Repeat step 3 while PTR  NULL • If PTR->DATA == ITEM, then • Set TEMP->LINK = PTR -> LINK, exit • else • TEMP = PTR • PTR = PTR -> LINK • Stop 3 cases: first node, last node, in-between node. (ex: if ITEM = 1000? if ITEM = 5000?) START Node A Node N Node B 1000 2000 3000 3500 4000 5000 START Node A Node N Node B 1000 2000 3000 3500 4000 5000 ….. 3500 ITEM TEMP PTR

  32. Print out a list (traverse a list) void print_list(list_pointer ptr){ printf(“The list ocntains: “); for ( ; ptr; ptr = ptr->link) printf(“%4d”, ptr->data); printf(“\n”); }

  33. List interface (list.h) typedef int Item; struct node { Item item; node *next; }; typedef node *link; typedef link Node; void construct(int); Node newNode(int); void deleteNode(Node); void insert(Node, Node); Node remove(Node); Node next(Node); Item item(Node);

  34. List Implementation (list.cpp) void deleteNode(link x) { insert(freelist, x); } void insert(link x, link t) { t->next = x->next; x->next = t; } link remove(link x) { link t = x->next; x->next = t->next; return t; } link next(link x) { return x->next; } Item item(link x) { return x->item; } #include <stdlib.h> #include "list.h" link freelist; void construct(int N) { freelist = new node[N+1]; for (int i = 0; i < N; i++) freelist[i].next = &freelist[i+1]; freelist[N].next = 0; } link newNode(int i) { link x = remove(freelist); x->item = i; x->next = x; return x; }

  35. 1 /* Fig. 12.3: fig12_03.c 2 Operating and maintaining a list */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 struct listNode { /* self-referential structure */ 7 char data; 8 struct listNode *nextPtr; 9 }; 10 11 typedefstruct listNode ListNode; 12 typedef ListNode *ListNodePtr; 13 14 void insert( ListNodePtr *, char ); 15 char delete( ListNodePtr *, char ); 16 int isEmpty( ListNodePtr ); 17 void printList( ListNodePtr ); 18 void instructions( void ); 19 20 int main() 21 { 22 ListNodePtr startPtr = NULL; 23 int choice; 24 char item; 25 Define struct Function prototypes Initialize variables

  36. 29 30 while ( choice != 3 ) { 31 32 switch ( choice ) { 33 case 1: 34 printf( "Enter a character: " ); 35 scanf( "\n%c", &item ); 36 insert( &startPtr, item ); 37 printList( startPtr ); 38 break; 39 case 2: 40 if ( !isEmpty( startPtr ) ) { 41 printf( "Enter character to be deleted: " ); 42 scanf( "\n%c", &item ); 43 44 if ( delete( &startPtr, item ) ) { 45 printf( "%c deleted.\n", item ); 46 printList( startPtr ); 47 } 48 else 49 printf( "%c not found.\n\n", item ); 50 } 51 else 52 printf( "List is empty.\n\n" ); 53 54 break; 26 instructions(); /* display the menu */ 27 printf( "? " ); 28 scanf( "%d", &choice ); Input choice switch statement

  37. 60 61 printf( "? " ); 62 scanf( "%d", &choice ); 63 } 64 65 printf( "End of run.\n" ); 66 return 0; 67 } 68 69 /* Print the instructions */ 70 void instructions( void ) 71 { 72 printf( "Enter your choice:\n" 73 " 1 to insert an element into the list.\n" 74 " 2 to delete an element from the list.\n" 75 " 3 to end.\n" ); 76 } 77 55 default: 56 printf( "Invalid choice.\n\n" ); 57 instructions(); 58 break; 59 }

  38. 91 92 while ( currentPtr != NULL && value > currentPtr->data ) { 93 previousPtr = currentPtr; /* walk to ... */ 94 currentPtr = currentPtr->nextPtr; /* ... next node */ 95 } 96 97 if ( previousPtr == NULL ) { 98 newPtr->nextPtr = *sPtr; 99 *sPtr = newPtr; 100 } 101 else { 102 previousPtr->nextPtr = newPtr; 103 newPtr->nextPtr = currentPtr; 104 } 105 } 106 else 107 printf( "%c not inserted. No memory available.\n", value ); 108 } 78 /* Insert a new value into the list in sorted order */ 109 79 void insert( ListNodePtr *sPtr, char value ) 80 { 81 ListNodePtr newPtr, previousPtr, currentPtr; 82 83 newPtr = malloc( sizeof( ListNode ) ); 84 85 if ( newPtr != NULL ) { /* is space available */ 86 newPtr->data = value; 87 newPtr->nextPtr = NULL; 88 89 previousPtr = NULL; 90 currentPtr = *sPtr;

  39. 121 else { 122 previousPtr = *sPtr; 123 currentPtr = ( *sPtr )->nextPtr; 124 125 while ( currentPtr != NULL && currentPtr->data != value ) { 126 previousPtr = currentPtr; /* walk to ... */ 127 currentPtr = currentPtr->nextPtr; /* ... next node */ 128 } 129 130 if ( currentPtr != NULL ) { 131 tempPtr = currentPtr; 132 previousPtr->nextPtr = currentPtr->nextPtr; 133 free( tempPtr ); 134 return value; 135 } 136 } 137 138 return '\0'; 139 } 140 110 /* Delete a list element */ 111 char delete( ListNodePtr *sPtr, char value ) 112 { 113 ListNodePtr previousPtr, currentPtr, tempPtr; 114 115 if ( value == ( *sPtr )->data ) { 116 tempPtr = *sPtr; 117 *sPtr = ( *sPtr )->nextPtr; /* de-thread the node */ 118 free( tempPtr ); /* free the de-threaded node */ 119 return value; 120 }

  40. 154 155 while ( currentPtr != NULL ) { 156 printf( "%c --> ", currentPtr->data ); 157 currentPtr = currentPtr->nextPtr; 158 } 159 160 printf( "NULL\n\n" ); 161 } 162 } 141 /* Return 1 if the list is empty, 0 otherwise */ 142 int isEmpty( ListNodePtr sPtr ) 143 { 144 return sPtr == NULL; 145 } 146 147 /* Print the list */ 148 void printList( ListNodePtr currentPtr ) 149 { 150 if ( currentPtr == NULL ) 151 printf( "List is empty.\n\n" ); 152 else { 153 printf( "The list is:\n" ); Enter your choice: 1 to insert an element into the list. 2 to delete an element from the list. 3 to end. ? 1 Enter a character: B The list is: B --> NULL ? 1 Enter a character: A The list is: A --> B --> NULL ? 1 Enter a character: C The list is: A --> B --> C --> NULL ? 2 Enter character to be deleted: D D not found. ? 2 Enter character to be deleted: B B deleted. The list is: A --> C --> NULL Program Output:

More Related