Download presentation
Presentation is loading. Please wait.
1
Elementary Data Structures
Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Elementary Data Structures Dale Roberts, Lecturer Computer Science, IUPUI
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
“Algorithms + Data Structures = Programs” (Wirth)
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: location: 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: location: 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? Q: When we delete 358, what happens to that location? Now, add item 498 onto the above list Q: Where would that item go? 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: location: 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: Reorganize the list: move the remaining elements. (space=9) data: ?(797)
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: location: Insert 505 onto the above list: Locate the appropriate position by performing a binary search should be stored in location 4. Create an ‘empty’ slot data: location: Insert 505 data:
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 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
Using Dynamically Allocated Storage
#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
13
List Implementation using Linked Lists
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
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 100 NULL pointer (points to nothing) Data member and pointer 500 … 3 2
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
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 data location 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? 345 358 490 501 513 724 797 701 561 555 345 358 490 501 513 724 797 701 561 555 498 345 358 490 501 513 724 797 701 561 555 498
17
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 300 5 2 500 NULL 3 3 100 4 4 200 1 5 400 2
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
Singly Linked List bat cat sat vat NULL
*Figure 4.1: Usual way to draw a linked list (p.139)
20
Linked List Insertion bat cat sat vat NULL mat
*Figure 4.2: Insert mat after cat (p.140)
21
Linked List Deletion bat cat mat sat vat NULL dangling
reference
22
Example: create a two-node list
20 NULL ptr typedef struct list_node *list_pointer; typedef struct list_node { int data; list_pointer link; }; list_pointer ptr =NULL
23
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; } 20 NULL ptr
24
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; } } 20 NULL temp ptr node
25
(a) before deletion (b)after deletion
ptr node trail = NULL ptr 20 NULL 20 NULL (a) before deletion (b)after deletion *Figure 4.7: List after the function call Delete(&ptr,NULL.ptr);(p.145)
26
List Deletion Delete the first node. 10 50 20 NULL 50 20 NULL
ptr trail node ptr 20 NULL 20 NULL (a) before deletion (b)after deletion Delete node other than the first node. ptr trail node ptr 20 NULL 20 NULL
27
10 50 20 NULL 10 20 NULL 10 50 20 NULL 50 20 NULL
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 20 NULL 20 NULL ptr node ptr 20 NULL 20 NULL
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
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 1000 START 2000 3000 4000 PTR PTR = LINK[PTR]
30
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 START 1000 2000 3000 4000 5000 Node A Node B PTR START 1000 2000 3000 4000 5000 Node A Node B 3500 Node N 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
Define struct Function prototypes Initialize variables
1 /* Fig. 12.3: fig12_03.c 2 Operating and maintaining a list */ 3 #include <stdio.h> Define struct Function prototypes Initialize variables 4 #include <stdlib.h> 5 6 struct listNode { /* self-referential structure */ 7 char data; 8 struct listNode *nextPtr; 9 }; 10 11 typedef struct 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
36
Input choice switch statement
29 30 while ( choice != 3 ) { 31 switch ( choice ) { case 1: printf( "Enter a character: " ); scanf( "\n%c", &item ); insert( &startPtr, item ); printList( startPtr ); break; case 2: if ( !isEmpty( startPtr ) ) { printf( "Enter character to be deleted: " ); scanf( "\n%c", &item ); 43 if ( delete( &startPtr, item ) ) { printf( "%c deleted.\n", item ); printList( startPtr ); } else printf( "%c not found.\n\n", item ); } else printf( "List is empty.\n\n" ); 53 break; 26 instructions(); /* display the menu */ 27 printf( "? " ); 28 scanf( "%d", &choice ); Input choice switch statement
37
60 printf( "? " ); 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" " 1 to insert an element into the list.\n" " 2 to delete an element from the list.\n" " 3 to end.\n" ); 76 } 77 default: printf( "Invalid choice.\n\n" ); instructions(); break; }
38
78 /* Insert a new value into the list in sorted order */
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 */ newPtr->data = value; newPtr->nextPtr = NULL; 88 previousPtr = NULL; currentPtr = *sPtr; 91 while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; /* walk to */ currentPtr = currentPtr->nextPtr; /* ... next node */ } 96 if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } else { previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } } else printf( "%c not inserted. No memory available.\n", value ); 108 } 109
39
else { previousPtr = *sPtr; currentPtr = ( *sPtr )->nextPtr; 124 while ( currentPtr != NULL && currentPtr->data != value ) { previousPtr = currentPtr; /* walk to */ currentPtr = currentPtr->nextPtr; /* ... next node */ } 129 if ( currentPtr != NULL ) { tempPtr = currentPtr; previousPtr->nextPtr = currentPtr->nextPtr; 110 /* Delete a list element */ 111 char delete( ListNodePtr *sPtr, char value ) 112 { ListNodePtr previousPtr, currentPtr, tempPtr; 114 if ( value == ( *sPtr )->data ) { tempPtr = *sPtr; *sPtr = ( *sPtr )->nextPtr; /* de-thread the node */ free( tempPtr ); /* free the de-threaded node */ return value; } free( tempPtr ); return value; } } 137 return '\0'; 139 } 140
40
Program Output: 141 /* Return 1 if the list is empty, 0 otherwise */
142 int isEmpty( ListNodePtr sPtr ) 143 { return sPtr == NULL; 145 } 146 Program Output: 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 Enter a character: A A --> B --> NULL Enter a character: C A --> B --> C --> NULL ? 2 Enter character to be deleted: D D not found. Enter character to be deleted: B B deleted. A --> C --> NULL 147 /* Print the list */ 148 void printList( ListNodePtr currentPtr ) 149 { if ( currentPtr == NULL ) 154 while ( currentPtr != NULL ) { printf( "%c --> ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } 159 printf( "NULL\n\n" ); } 162 } printf( "List is empty.\n\n" ); else { printf( "The list is:\n" );
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.