Advanced Pointers and Structures Pointers in structures Memory allocation Linked Lists –Stacks and queues Trees –Binary tree example.

Slides:



Advertisements
Similar presentations
Data Structure Lecture-5
Advertisements

Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
CS252: Systems Programming Ninghui Li Program Interview Questions.
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.
Advanced Data Structures Stack –a stack is dynamic data items in a linear order, such that the item first "pushed" in is the last item "popped" out. Think.
C Programming : Elementary Data Structures 2009/04/22 Jaemin
Computer Science C++ High School Level By Guillermo Moreno.
Chapter 13 Pointers and Linked Lists. Nodes and Linked Lists Linked list: A sequence of nodes in which each node is linked or connected to the node preceding.
Linked Lists in C and C++ CS-2303, C-Term Linked Lists in C and C++ CS-2303 System Programming Concepts (Slides include materials from The C Programming.
More on Dynamic Memory Allocation Seokhee Jeon Department of Computer Engineering Kyung Hee University 1 Illustrations, examples, and text in the lecture.
Linked Lists in C and C++ By Ravi Prakash PGT(CS).
C Programming - Lecture 7 This lecture we will learn: –How to write documentation. Internal docs. External docs. User docs. (But not much about this).
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Lists and TreesCS-2301 D-term Data Structures — Lists and Trees CS-2301 System Programming D-term 2009 (Slides include materials from The C Programming.
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
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.
Data Structures — Lists and Trees CS-2301, B-Term Data Structures — Lists and Trees CS-2301, System Programming for Non-Majors (Slides include materials.
C Programming –Application of Pointers to Linked List and Binary Tree In this lecture we learn about: –Linked Lists –Binary Trees.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
1 Data Structures Lists and Trees. 2 Real-Life Computational Problems All about organizing data! –What shape the data should have to solve your problem.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
Data Structures Week 8 Further Data Structures The story so far  Saw some fundamental operations as well as advanced operations on arrays, stacks, and.
Lists 1. Introduction Data: A finite sequence of data items. Operations: Construction: Create an empty list Empty: Check if list is empty Insert: Add.
Introduction to Data Structures Systems Programming Concepts.
Data Structures: Advanced Damian Gordon. Advanced Data Structure We’ll look at: – Linked Lists – Trees – Stacks – Queues.
Programming Practice 3 - Dynamic Data Structure
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a wrappered function? –How to assess efficiency. –What is a clean interface?
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Concepts of Algorithms CSC-244 Unit 19 & 20 Binary Search Tree (BST) Shahid Iqbal Lone Computer College Qassim University K.S.A.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
1 Midterm 1 on Friday February 12 Closed book, closed notes No computer can be used 50 minutes 4 questions Write a function Write program fragment Explain.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Popping Items Off a Stack Using a Function Lesson xx
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
5.13 Recursion Recursive functions Functions that call themselves
12 C Data Structures.
12 C Data Structures.
ENEE150 Discussion 09 Section 0101 Adam Wang.
Lecture 22 Binary Search Trees Chapter 10 of textbook
Binary Search Trees.
Tree data structure.
Chapter 20: Binary Trees.
Programmazione I a.a. 2017/2018.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Lists.
Chapter 21: Binary Trees.
Tree data structure.
Popping Items Off a Stack Lesson xx
Lesson Objectives Aims
Dynamic Memory Allocation
Review & Lab assignments
Linked Lists in C and C++
CS6045: Advanced Algorithms
Priority Queue and Heap
Presentation transcript:

Advanced Pointers and Structures Pointers in structures Memory allocation Linked Lists –Stacks and queues Trees –Binary tree example

Structs which contain themselves Sometimes programmers want structs in C to contain themselves. For example, we might design an electronic dictionary which has a struct for each word and we might want to refer to synonyms which are also word structures. word1:run synonym1 synonym2 word2: sprint synonym1 synonym2 word3: jog synonym1 synonym2

How structs can contain themselves Clearly a struct cannot literally contain itself. But it can contain a pointer to the same type of struct struct silly_struct { /* This doesn't work */ … struct silly_struct s1; }; struct good_struct { /* This does work */ … struct *good_struct s2; };

Memory allocation How to allocate memory dynamically? –void *malloc(unsigned int); –Example: char *str; str = malloc(80); Now str can hold up to 80 Bytes.

Freeing memory To free memory that was allocated using malloc we use free function. free returns the memory pointed by a given pointer to the OS. free(pointer) pointer = NULL:

The linked list - a common use of structs which contain themselves Imagine we are reading lines from a file but don't know how many lines will be read. We need a structure which can extend itself. This is known as a linked list. By passing the value of the head of the list to a function we can pass ALL the information.

How to set up a linked list typedef struct list_item { information in each item struct list_item *nextptr; } LIST_ITEM; This structure (where information is what you want each "node" of your linked list to contain). It is important that the nextptr of the last bit of the list contains NULL so that you know when to stop. NULL head of list

Example -- Address book typedef struct list { char name[MAXLEN]; char address[MAXLEN]; char phone[MAXLEN]; struct list *next; } ADDRESS; ADDRESS *myabook= NULL; /* Set the head of the list */

Linked list concepts NULL head of list Adding an item to the middle of the list NULL head of list new item points at next item move this link Deleting an item from the middle of the list NULL head of list move this link delete this node

Stacks and Queues Stacks use push and pop –Push add a node at the head of a linked list. –Pop remove the head node Queues –Adding nodes at the head of the list –Removing nodes at the end of a list So we need 2 pointers, one for the head and one for the tail.

Tree A tree is a method for data (for example a dictionary of words) where we wish to easily be able to add items and find items Each element in the tree can lead to two (or more) further elements. struct TreeNode {... Data part TreeNode* child1; TreeNode* child2;... };

Binary Tree – Structure Example A binary tree is a data “structure” The basic data structure is a node which includes: –The data contained in that node –Pointers to two children nodes (left and right) 2 pointers == binary Left node pointer points to a node with data that is less than the current node Right node pointer points to a node with data that is greater than the current node All nodes to the left contain data less All nodes to the right contain data greater –A leaf node is a node with no children

Binary Tree: Adding a node Simply add a leaf to the tree. –Add

Binary Tree All nodes on the left are less than 10 and all on the right are greater than 10 Add 15?

Binary Tree All nodes on the left are less than 10 and all on the right are greater than 10 Add the value 9? 15

Insert All nodes on the left are less than 10 and all on the right are greater than 10 Add 25? 15 9

Insert All nodes on the left are less than 10 and all on the right are greater than 10 Remove 5?

Removing a node from a binary tree Node has no children –Simply remove it from tree Node has one child –Remove the node and replace it with it’s child Node has two children –Replace the node’s value with (2 options): the left-most value of the right tree. the right-most value of the left tree.

Remove Leaf All nodes on the left are less than 10 and all on the right are greater than 10 Remove 8?

Remove node with one child All nodes on the left are less than 10 and all on the right are greater than 10 Remove 20?

Remove node with two children Replace value with left-most value of the right tree All nodes on the left are less than 10 and all on the right are greater than 10 Remove 10? 15 25

Remove node with two children Replace value with left-most value of the right tree All nodes on the left are less than 15 and all on the right are greater than 15

The Binary Tree Node Structure struct BinaryTreeNode { int value; BinaryTreeNode* left; BinaryTreeNode* right; };

Removing a node from a binary tree RemoveNode(node* head) { if (head->left == null) { node* t = head; head = head->right; free_node(t); } else if (head->right == null) { node* t = head; head = head->left; free_node(t); } else { node * t = head->right; while(t->left) t = t->left; head->value = t->value; RemoveNode(t); }

The binary tree NULL typedef struct tree { char word[100]; struct tree *left; struct tree *right; } TREE;

Binary Tree Pros & Cons Finding an element is O(log n) Adding an element is O(log n) – O(1) if we already know where to add it. Deleting an element may be complex Programming complexity is higher than a linked list (just about)

Deleting an entire binary tree I think this code is elegant and worth looking at: void delete_tree (TREE *ptr) { if (ptr == NULL) return; delete_tree(ptr->left); delete_tree(ptr->right); free (ptr); } We can delete the whole tree with: delete_tree(root_of_tree);

A binary tree example - words.c /************************************************************** * words -- scan a file and print out a list of words * * in ASCII order. * * * * Usage: * * words * **************************************************************/ #include struct node { struct node *left; /* tree to the left */ struct node *right; /* tree to the right */ char *word; /* word for this tree */ }; /* the top of the tree */ static struct node *root = NULL;

void memory_error(void) { fprintf(stderr, "Error:Out of memory\n"); exit(8); } char *save_string(char *string) { char *new_string; /* where we are going to put string */ new_string = malloc((unsigned) (strlen(string) + 1)); if (new_string == NULL) memory_error(); strcpy(new_string, string); return (new_string); }

void enter(struct node **node, char *word) { int result; /* result of strcmp */ char *save_string(char *); /* save a string on the heap */ /* If the current node is null, we have reached the bottom * of the tree and must create a new node. */ if ((*node) == NULL) { /* Allocate memory for a new node */ (*node) = malloc(sizeof(struct node)); if ((*node) == NULL)memory_error(); /* Initialize the new node */ (*node)->left = NULL; (*node)->right = NULL; (*node)->word = save_string(word); return; } /* Check to see where the word goes */ result = strcmp((*node)->word, word); /* The current node already contains the word, no entry necessary */ if (result == 0) return; /* The word must be entered in the left or right sub-tree */ if (result < 0) enter(&(*node)->right, word); else enter(&(*node)->left, word); }

void scan(char *name) { char word[100]; /* word we are working on */ int index; /* index into the word */ int ch; /* current character */ FILE *in_file; /* input file */ in_file = fopen(name, "r"); if (in_file == NULL) { fprintf(stderr, "Error:Unable to open %s\n", name); exit(8); } while (1) { /* scan past the whitespace */ while (1) { ch = fgetc(in_file); if (isalpha(ch) || (ch == EOF)) break; } if (ch == EOF) break; word[0] = ch; for (index = 1;index < sizeof(word); ++index) { ch = fgetc(in_file); if (!isalpha(ch)) break; word[index] = ch; } /* put a null on the end */ word[index] = '\0'; enter(&root, word); } fclose(in_file); }

void print_tree(struct node *top) { if (top == NULL) return; /* short tree */ print_tree(top->left); printf("%s\n", top->word); print_tree(top->right); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Error:Wrong number of parameters\n"); fprintf(stderr, " on the command line\n"); fprintf(stderr, "Usage is:\n"); fprintf(stderr, " words 'file'\n"); exit(8); } scan(argv[1]); print_tree(root); return (0); }