1 CS 201 Dynamic Data Structures (3) Debzani Deb.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

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.
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Module R2 Overview. Process queues As processes enter the system and transition from state to state, they are stored queues. There may be many different.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
C Programming : Elementary Data Structures 2009/04/22 Jaemin
Kernighan/Ritchie: Kelley/Pohl:
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 CS 201 Dynamic Data Structures (2) Debzani Deb.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 CS 201 Dynamic Data Structures and Function Pointers Debzani Deb.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Chapter 14 Dynamic Data Structures Instructor: Alkar & Demirer.
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Grade 12 Computer Studies HG
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Stack and Heap Memory Stack resident variables include:
Pointers OVERVIEW.
Dynamic memory allocation and Pointers Lecture 4.
Introduction to Data Structures Systems Programming Concepts.
CS342 Data Structures End-of-semester Review S2002.
Programming Practice 3 - Dynamic Data Structure
Linked Lists EENG 212 ALGORITHMS And DATA STRUCTURES.
Pointers *, &, array similarities, functions, sizeof.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
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.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Stack and Heap Memory Stack resident variables include:
Pointers and Linked Lists
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
Lectures linked lists Chapter 6 of textbook
Data Structure Interview Question and Answers
12 C Data Structures.
Introduction to Data Structures
An Introduction to Pointers
Dynamic Memory Allocation
Memory Allocation CS 217.
Review & Lab assignments
Outline Defining and using Pointers Operations on pointers
Pointers & Dynamic Data Structures
(1 - 2) Introduction to C Data Structures & Abstract Data Types
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

1 CS 201 Dynamic Data Structures (3) Debzani Deb

2 Overview Grading Exam 2 review Queue Binary Tree

3 Grading Exam 2: Highest 47, average 28. How Final grading will be done?  Labs : 50% (Do not assume linear distribution)  Quiz: 2% each (Last one is coming…)  Exam 1 & 2 : Each 11% (Look for the scaled grades)  Final Exam: 20% Special offer: There will be an exam next week  Syllabus same as exam 2, Standard same as exam 2.  You have the option of replacing your Exam 1 & 2 grade with the result of that single test.  Can appear only if you have the probability of getting a F or D.  me with the intent within next Wednesday.

4 Exam 2 : Review

5 Exam 2:Question 1.a 4: double average(int *array); 6: int main(void) 7: { 8: int numberOfMeasurements, i; 9:int *measurements; 10: double avg; 12: printf("Number of measurements?\n"); 13:scanf("%d", &numberOfMeasurements); 15:measurements = (int *)malloc(numberOfMeasurements); 17: for(i=0; i<numberOfMeasurements; i++) { 18: scanf("%d", measurements + i); 19: } 21: avg = average(&measurements); 23: printf("Average of the measurements: %lf\n", avg); 25:return 0; 26:} If you compile, there will be no syntax error, only one warning code.c:21: warning: passing arg 1 of `average' from incompatible pointer type The code won’t produce desired output. void *malloc(size_t number_of_bytes) size_t argument type is defined in stdlib.h and is an unsigned type sizeof operator returns the size in bytes of its operand X

6 Exam 2 : Question 1.a 28: double average(int *array) 29: { 30: int i, sum; 31: double avg; 32: 33: for(i=0; i<sizeof(array); i++) { 34: sum += array[i]; 35: } 36: avg = sum / sizeof(array); 37: 38: return avg; 39:} 28: double average(int *array, int size) 29: { 30: int i, sum; 31: double avg; 32: 33: for(i=0; i<size; i++) { 34: sum += array[i]; 35: } 36: avg = (double) sum / size; 37: 38: return avg; 39:} CORRECTED It is never possible, using sizeof, to find out how long an array a pointer points to; you must have a genuine array name instead. int ar[5]; int *ip = ar; printf("sizeof(ar) is %d\n", sizeof(ar)); printf("sizeof(ip) is %d\n", sizeof(ip));

7 Exam 2 : Question 2.a Write a function Occurrence which takes two arguments, a string and a character, and returns the number of times the character appears in the string. For example, Occurrence ("Senselessness", 's') should return 6. int Occurrence (char * str, char c) { int i, count = 0; for (i = 0 ; str[i] != '\0' ; i++) if (str[i] == c) count++ ; return(count) ; } Common mistakes  Use of sizeof(str) to determine the string length. WRONG!  Use strlen(str) instead  Use of NULL instead of ‘\0’ to check the end of the string.

8 Exam 2 : Question 2.c Describe the flaw in the following function. /* * Forms the plural of noun by adding an 's'. */ char * add_s(const char *noun) { char result[100]; strcpy(result, noun); strcat(result, "s"); return (result); } Answer: It returns the address of a locally declared array as the function value. This space is deallocated as soon as the function returns.

9 Exam 2 : Question 4.a Given the following type and variable declarations, typedef union { char guardian[25]; char employer[35]; } contact_t; typedef struct { int age; contact_t contact; } person_t; person_t newcomer; What memory will be allocated for variable newcomer? Answer: one integer and 35 characters

10 Exam 2 : Question 5.a Consider this fragment of a C program. int main(void) { char *stringp; stringp = (char *)calloc(10, sizeof(char)); } In which portion of the memory, variable stringp and the 10- element array of characters will be allocated? Answer: stringp: Stack, 10-element char array: Heap

11 Linked List basics (Again) A linked list is a sequence of nodes in which each node but the last contains the address of the next node. typedef struct list_node_s { int digit; struct list_node_s *restp; } list_node_t; list_node_t *n1_p, *n2_p; n1_p = (list_node_t *) malloc (sizeof(list_node_t)); n2_p = (list_node_t *) malloc (sizeof(list_node_t)); n1_p -> digit = 5; n2_p -> digit = 7; n1_p -> restp = n2_p; n2_p -> restp = NULL; 5 n1_p digit restp 7 n2_p digit restp X

12 Exam 2 : Question 5.b If listp is a pointer to the first node of a linked list containing the data , what is displayed by the following code fragment? for (nextp = listp; nextp->restp != NULL; nextp = nextp->restp) printf("%4d",nextp->data); 8 listp datarestp 14 datarestp 7 datarestp 6 datarestp 2 data X restp nextp FOR LOOP: Initialization Condition check Execute body Increment Condition check Output Condition Fails !!!

13 Exam 2 : Question 5.c Write a function display_list that takes a parameter of type node_t * and displays the data from each linked list element on a separate line. void display_list(node_t *listp) { if (listp != NULL) { printf("%4d\n", listp->data); display_list(listp->restp); } Common mistake for (nextp = listp; nextp->restp != NULL; nextp = nextp->restp) printf("%4d",nextp->data);

14 Exam 2 : Question 5.d insertLast (Dlist listp, double val), inserts a double number as the last element of DList representing list of double numbers.  Recursively/iteratively find the last node of the list.  Allocate memory for the new node, copy val to the data field, assign NULL to the pointer field (as last node) and then connect the new node to the list.

15 Queue

16 Representing a Queue with a linked list Like a queue of people waiting Push at the Head (i.e at the end of the list). Pop from the Bottom (i.e from the front of the list) First In First Out (FIFO) restp 7 Head restp 5 3 X Front End Push Pop

17 Push on Queue typedef struct list_node_s { int digit; struct list_node_s *restp; } list_node_t; Push is same as stack (at Head) list_node_t * push (list_node_t * qHead, int v) { list_node_t * p = (list_node_t *) malloc(sizeof(list_node_t)); p -> digit = v; p -> restp = qHead; return p; } Pointer to the current head of the queue Return pointer to the new head of the queue Return the new node as the head of the queue int main(void) { list_node_t * qHead = NULL; /* Function call for push*/ qHead = push(qHead, 3); qHead = push(qHead, 5); return 0; }

18 Pop from Queue (from the bottom) list_node_t * pop (list_node_t * qHead, int * v) { list_node_t * qEnd, * qFront = NULL; if (qHead -> restp = NULL) { // Queue has only one element *v = qHead ->digit; free (qHead); return NULL; } for (qEnd = qHead; qEnd ->restp != NULL; qEnd = qEnd -> restp) qFront = qEnd; *v = qEnd -> digit; qFront -> restp = NULL; free(qEnd); return qHead; } Can we write this more efficiently?

19 Queue (Summary) You could implement it as an array too. You could make a hybrid of stack/queue to access at either end. Common design for process scheduling, event processing, buffering, input/output etc. In our design push is constant time, but pop is O(n) linear time (where n is the number of elements in the queue). If we record two pointers (front and end) instead of only one pointer pointing to the head of the list – both push and pop would have constant time.  See the implementation in your textbook.

20 Circular and double linked list Circular linked list pHead -> restp -> restp -> restp -> restp = pHead; Double linked list struct dblLink { int digit; struct dblLink * pNext, pPrev; } 9 pHead digitrestp 7 digitrestp 5 digitrestp 3 digitrestp 9 pHead digitpNext X pPrev 7 digitpNextpPrev 5 digit X pNextpPrev pTail

21 Trees Non linear data structures  Elements can have two or more children.  Useful for sorting, graph algorithms, searching etc. A simple example – binary tree  Each element has 0-2 children.  Elements with no children are called a leaf.  Each element has 0-1 parents.  Elements with no parents are called a root.

22 Binary Tree Structure with two children, may maintain pointer to the parent node too. typedef struct node_s { int data; struct node_s *leftp, *rightp; // struct node_s *parentp; } node_t; data parentp leftprightp

23 Binary Search Tree Useful for sorting  Can make an invariant like: all elements in leftp are less than data, all elements in rightp are greater than data. Useful for searching  With an invariant such as above, you can find an element in the tree in O(log 2 n) time.  Binary search tree is a very common abstraction to maintain.  Many algorithms are there.