Elementary Data Structures

Slides:



Advertisements
Similar presentations
Chapter 4 Lists Pointers Singly Linked Lists
Advertisements

Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
CS Data Structures Chapter 4 Lists.
Introduction to C Programming CE Lecture 19 Linear Linked Lists.
Linked List (I) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
UNIT-2. Singly Linked List Doubly Linked List Circular Linked List Representing Stack with Linked List. Representing Queue with Linked List.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Implementation of Linked List For more notes and topics visit: eITnotes.com.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
UNIT 1 Data Structures Using C Linked List By Rohit Khokher Department of Computer Science, Vidya College of Engineering, Meerut, India.
Introduction to Data Structures Systems Programming.
CSC 211 Data Structures Lecture 23
Linked Lists part 2 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
Data Structures and Algorithms Lecture 1 Instructor: Quratulain Date: 1 st Sep, 2009.
Introduction to Data Structures Systems Programming Concepts.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Programming Practice 3 - Dynamic Data Structure
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Data Structures Dale Roberts, Lecturer Computer Science,
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Elementary Data Structures Array Lists Array Lists Dale.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Elementary Data Structures Linked Lists Linked Lists Dale.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Dale Roberts, Lecturer Data Structure.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Data Structures - Prabir Sarkar. AGENDA Stack Queue Linked List Trees Graphs Searching and Sorting Algorithm.
CHAPTER 51 LINKED LISTS. Introduction link list is a linear array collection of data elements called nodes, where the linear order is given by means of.
CPT: Lists/ Computer Programming Techniques Semester 1, 1998 Objective of these slides: –to describe linked lists in C 15. Lists.
UNIT-II Topics to be covered Singly linked list Circular linked list
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
Lecture 6 of Computer Science II
Pointers and Linked Lists
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Dynamic Allocation Review Structure and list processing
Linked List :: Basic Concepts
Pointers and Linked Lists
5.13 Recursion Recursive functions Functions that call themselves
Lectures linked lists Chapter 6 of textbook
Linked Lists Chapter 6 Section 6.4 – 6.6
12 C Data Structures.
Data Structure and Algorithms
Prepared by, Jesmin Akhter, Lecturer, IIT, JU
Data Structure Dr. Mohamed Khafagy.
UNIT-3 LINKED LIST.
EEE2108: Programming for Engineers Chapter 4. Linked Lists
Introduction to Data Structures
CSCE 210 Data Structures and Algorithms
Linked List Sudeshna Sarkar.
Programmazione I a.a. 2017/2018.
CSCE 3110 Data Structures & Algorithm Analysis
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Lists.
Popping Items Off a Stack Lesson xx
Further Data Structures
Programming Abstractions
Review & Lab assignments
Linked List.
Chapter 16 Linked Structures
Data Structures & Algorithms
Abstract Data Types Stacks CSCI 240
21 Data Structures.
Presentation transcript:

Elementary Data Structures 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 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

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

“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.

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

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? 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

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 Reorganize the list: move the remaining elements. (space=9) data: 345 490 501 513 555 561 701 724 797 ?(797)

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

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; }

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

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

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

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.

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

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

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

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

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.

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

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

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

Example: create a two-node list 10  20 NULL ptr typedef struct list_node *list_pointer; typedef struct list_node { int data; list_pointer link; }; list_pointer ptr =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; } 10  20 NULL ptr

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; } } 50  10  20 NULL temp ptr node

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

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

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 10  50  20 NULL 10  20 NULL ptr node ptr 10  50  20 NULL 50  20 NULL

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

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]

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?)

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

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”); }

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);

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;

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

Input choice switch statement 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

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 }

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 */ 86 newPtr->data = value; 87 newPtr->nextPtr = NULL; 88 89 previousPtr = NULL; 90 currentPtr = *sPtr; 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 } 109

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; 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 } 133 free( tempPtr ); 134 return value; 135 } 136 } 137 138 return '\0'; 139 } 140

Program Output: 141 /* Return 1 if the list is empty, 0 otherwise */ 142 int isEmpty( ListNodePtr sPtr ) 143 { 144 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 { 150 if ( currentPtr == NULL ) 154 155 while ( currentPtr != NULL ) { 156 printf( "%c --> ", currentPtr->data ); 157 currentPtr = currentPtr->nextPtr; 158 } 159 160 printf( "NULL\n\n" ); 161 } 162 } 151 printf( "List is empty.\n\n" ); 152 else { 153 printf( "The list is:\n" );