1 CS 201 Dynamic Data Structures and Function Pointers Debzani Deb.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Pointers.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Introduction to Memory Management. 2 General Structure of Run-Time Memory.
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.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
1 CS 201 Dynamic Data Structures (3) Debzani Deb.
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
Memory Allocation. Three kinds of memory Fixed memory Stack memory Heap memory.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
1 CS 201 Dynamic Data Structures (2) Debzani Deb.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
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.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
CHAPTER 71 TREE. Binary Tree A binary tree T is a finite set of one or more nodes such that: (a) T is empty or (b) There is a specially designated node.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Lecture No.01 Data Structures Dr. Sohail Aslam
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Introduction to Data Structures. Definition Data structure is representation of the logical relationship existing between individual elements of data.
Data Structures Week 5 Further Data Structures The story so far  We understand the notion of an abstract data type.  Saw some fundamental operations.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
1 Writing a Good Program 8. Elementary Data Structure.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
CS342 Data Structures End-of-semester Review S2002.
Programming Practice 3 - Dynamic Data Structure
Copyright © 2002 Pearson Education, Inc. Slide 1.
Programming Abstractions Cynthia Lee CS106X. Topics:  Priority Queue › Linked List implementation › Heap data structure implementation  TODAY’S TOPICS.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
CISC220 Fall 2009 James Atlas Dec 07: Final Exam Review.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Data Structures David Kauchak cs302 Spring Data Structures What is a data structure? Way of storing data that facilitates particular operations.
Data Structure and Algorithms
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Pointers and Linked Lists
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Pointers and Linked Lists
Introduction to Linked Lists
Sorted Linked List Same objective as a linked list, but it should be sorted Sorting can be custom according to the type of nodes Offers speedups over non-sorted.
Lectures linked lists Chapter 6 of textbook
Data Structure Interview Question and Answers
12 C Data Structures.
Data Structures and Algorithms
Programming Abstractions
Chapter 8: Data Abstractions
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Introduction to Linked Lists
Pointers and Linked Lists
Review & Lab assignments
Data Structures and Algorithms
Presentation transcript:

1 CS 201 Dynamic Data Structures and Function Pointers Debzani Deb

2 Overview Queue Circular and doubly link list Binary Tree Function Pointers Grading Discussion

3 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

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

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

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

7 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

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

9 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

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

11 Function Pointers

12 Addressing Functions Variables reside in program’s memory space. Address of a variable can be found with & operator. int main(void) { int a = 2; printf(“Adddress of a: %p\n”, &a); return 0; } Function resides in program’s memory space as well. void func(int b) { printf(“b = %d\n”,b); } int main(void) { printf(“Adddress of \n main(): %p\n func(): %p\n printf(): %p\n”, &main, &func, &printf); return 0; } … … 2 … a22F24C Address of a : 0022F24C Address of main(): 0088F24A func(): 0088F6CC Printf(): 0088FF2A & operator returns function address 0088F24A main 0088F6CC func 0088FF2A printf

13 Functions in address space Stack frame for main Stack frame for func Heap Global, static variables main func Code Machine language instructions of a function are found here. Static data Stack Frames Variables declared inside a function can be found here. Dynamically allocated variables Order of the memory components (code, static data, stack and heap) may be different depending on the memory models utilized by the compiler.

14 Function Pointers (1) Pointer to Variable declaration: int i; pointer declaration: int *ip = &i; Pointer to Function declaration: int f (int arg); pointer declaration: int (*fp) (int arg) = &f; By analogy with ordinary variables, the address of a function can be stored in a pointer variable : the function pointer. Defines a function pointer fp, pointing to a function with one integer argument and returning an integer. Function pointer and the function it points to must be compatible in return type and argument list. parentheses are essential for maintaining precedence Argument name is optional

15 Function Pointers (2) void f (int); void (*fp) (int); fp may points to a function of the form void f (int). Like Arrays, Function name is an address of the beginning of the function. Therefore: fp = f; fp = &f; Both assign the same location, i.e. the beginning address of the code of function f to the function pointer fp. Creating your own function pointer type can be useful sometime. typedef int (*fp_t) (int); fp_t fptr = &func; The identifies fp_t is now a synonym for the type “pointer to a function that takes an int argument and returns int”.

16 Using Function Pointers double ari (int a, int b) { return (a+b)/2; } // Arithmetic mean double geo (int a, int b) { return sqrt (a*b); } // Geometric mean double (*fp) (int a, int b) = NULL; Assigning an address to a function pointer: fp = &ari;/* assignment using addresses */ fp = geo;/* short form */ Calling a function using a function pointer: double result = (*fp)(10, 20); /* explicit dereferencing */ double result = fp(10, 20); /* short form, still same */ Array of function pointers: double (*fp[2]) (int, int) = {ari, geo}; for(i=0; i<2; i++) printf(“Mean %d: %.2f\n”, i, fp[i](10, 20); Mean 0: 15 Mean 1: 14.14

17 Passing a function pointer as an argument to another function Function pointers can be used to pass functions as arguments to another function. double mean (int a, int b, double (*fp) (int, int) ) { double result = (*fp) (a,b); return result; } Function is called by passing just a function name (i.e. a pointer to the address of the function code in short form) double ari_mean = mean (10, 20, ari); double geo_mean = mean (10, 20, geo);

18 Grading

19 Grading How Final grading will be done?  Labs : 50%  Quiz: 2% each : Total 4 (Last one is coming…)  Exam 1 & 2 : Each 11% (Look for the scaled grades)  Final Exam: 20% A, B, C & D will be defined by curve fitting.

20 Exam 1: Histogram (on scaled data)

21 Exam 2: Histogram (on scaled data)

22 Suggestions (summarized) Person 1: Writing code that actually compile is too much considering the time constraints, instead suggested pseudo code/algorithm. Person 2: Coding is difficult and error prone, suggested critical thinking questions, extra credit lab. Person 3: Suggested extra credit based on gdb. Person 4 & 5: Everybody gets same time for both tests, no extra credit, scale/curve the result. Person 6 : Median, scale/curve the result.

23 Important !!! Special Exam: There will be an exam early 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 today. Your TA (Fuad) will be in Bozeman from this Friday.  Make appointment with him by sending and clear all the pending labs by next week. Check lab 7 & 9 grades next Monday.