Chapter 6 Structures By C. Shing ITEC Dept Radford University.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Stack and Queues using Linked Structures Kruse and Ryba Ch 4.
CSEB324 Data Structures & Algorithms
LIST PROCESSING.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
CSCI2100B Linked List Jeffrey
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.
Programming in C Chapter 10 Structures and Unions
Data Structure Lecture-5
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Chapter 17 Linked List Saurav Karmakar Spring 2007.
Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
CS Data Structures II Review COSC 2006 April 14, 2017
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
C Programming : Elementary Data Structures 2009/04/22 Jaemin
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Structures and Lists (and maybe stacks) Chapters 9-10.
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.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
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.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Introduction to Data Structures Systems Programming.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CSC 211 Data Structures Lecture 23
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
CSC2100B Tutorial 2 List and stack implementation.
Chapter 2 Simple Data Types By C. Shing ITEC Dept Radford University.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Chapter 19 C++ Data Structures By C. Shing ITEC Dept Radford University.
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
Introduction to Data Structures Systems Programming Concepts.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Programming Practice 3 - Dynamic Data Structure
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
Stacks This presentation shows – how to implement the stack – how it can be used in real applications.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
Data Structures - Prabir Sarkar. AGENDA Stack Queue Linked List Trees Graphs Searching and Sorting Algorithm.
Chapter 8 Bit Operations By C. Shing ITEC Dept Radford University.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
DATA STRUCURES II CSC QUIZ 1. What is Data Structure ? 2. Mention the classifications of data structure giving example of each. 3. Briefly explain.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Abstract Data Types Queues Dale Roberts, Lecturer
Chapter 12 – Data Structures
CS 201 Data Structures and Algorithms
5.13 Recursion Recursive functions Functions that call themselves
Stacks – review A Last-In First-Out (LIFO) structure Basic Operations:
12 C Data Structures.
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.
Stacks – review A Last-In First-Out (LIFO) structure Basic Operations:
CE 221 Data Structures and Algorithms
Review & Lab assignments
By C. Shing ITEC Dept Radford University
EE 312 Final Exam Review.
17CS1102 DATA STRUCTURES © 2016 KL University – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS.
Structures EECS July 2019.
Presentation transcript:

Chapter 6 Structures By C. Shing ITEC Dept Radford University

Slide 2 Objectives Understand how to use structures Understand how to call function by passing structures Understand how to use unions

Slide 3 Structure A record that can store different data types Declared data type (struct structure_name) first as struct [structure_name] { type1 fieldname1; … } [variable_lists]; Then define a new type by typedef struct structure_name structure_type; or typedef struct { type1 fieldname1; … } structure_type;

Slide 4 Structure (Cont.) Example: struct student_record { char lastname[30]; char firstname[15]; float gpa; }; typedef struct student_record student_rec;

Slide 5 Structure (Cont.) Declared variables then as struct structure_name variable_list; Or use structure_type variable_list; Example: struct student_record student1, student2; struct student_record student[100]; or student_rec student[100];…

Slide 6 Initialize Structure Similar to initialize an array Fill in 0 or NULL if not enough data Example: student_rec student1={“Doe”, “John”, 2.0}; student_rec student_any;

Slide 7 Read in Structure from Keyboard Example: scanf(“%s%s%f”, student1.lastname, student1.firstname, &student1.gpa); // data: Doe John 2.0 Example1

Slide 8 Structure Assignment Assign field: student_any.lastname=student1.lastname; Example: Program, DataProgramData Assign whole structure: Example: student_any= student1;

Slide 9 Pointer and Structure If a pointer p to a stucture_type variable, then to access a field (or member), use p -> fieldname Or (*p).fieldname Example 2

Slide 10 Pointer and Structure (Cont.) Example: student_rec student1={“Doe”, “John”, 2.0}, *student_pointer=&student1; Then student_pointer->lastname = “Doe”; (*student_pointer).firstname = “John”; student_pointer->gpa=2.0; (student_pointer->firstname)[3]=‘n’; (*(student_pointer->firstname))+2=‘L’;

Slide 11 Pass Structure to Function Use pass-by-value: pass a copy of structure, Default, not efficient If structure is changed after function call, must return the structure_type result The returned result must be assigned back to the original variable Example: student1=change_gpa (student1); student_rec change_gpa (student_rec student_any) { printf(“Please enter new gpa:\n”); scanf(“%f”, &student_any.gpa); return student_any; } Example 3

Slide 12 Pass Structure to Function (Cont.) Use pass-by-reference: pass in pointer, very efficient Example: change_gpa (&student1); void change_gpa (student_rec *student_pointer) { printf(“Please enter new gpa:\n”); scanf(“%f”, &student_pointer->gpa); } Example 4

Slide 13 Sort Structures Problem: input data into array of structures And then sort them Data:

Slide 14 Sort Structures (Cont.) struct request { int number; double duration; }; typedef struct request requesttype; void input(requesttype request[], int *count);

Slide 15 Sort Structures (Cont.) int main(void) { requesttype request[1000]; int count=0; … input(request, &count); sort_struct(request, count); }

Slide 16 Sort Structures (Cont.) void input(requesttype request[], int *count) { int i; for (i=0; scanf("%d", &request[i].number), request[i].number !=0; i++) { scanf("%lf", &request[i]. duration); … (*count)++; }

Slide 17 Sort Structures (Cont.) void sort_struct (requesttype w[], int n) { int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j) if (w[i].duration > w[j].duration) swap (&w[i], &w[j]); }

Slide 18 Sort Structures (Cont.) void swap (requesttype *s, requesttype *t) { requesttype tmp; tmp=*s; *s=*t; *t=tmp; }

Slide 19 Sort Structures – Another Way (Cont.) void sort_struct (requesttype w[], int n) { int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j) if (w[i].duration > w[j].duration) { swapInt (&w[i], &w[j]); swapDouble (&w[i], &w[j]); }

Slide 20 Sort Structures – Another Way (Cont.) void swapInt (requesttype *s, requesttype *t) { int tmp; tmp=s->number; s->number=t->number; t->number=tmp; }

Slide 21 Sort Stuctures – Another Way (Cont.) void swapDouble (requesttype *s, requesttype *t) { double tmp; tmp=s->duration; s->duration=t->duration; t->duration=tmp; }

Slide 22 Example Helpful Code Data Sort Student Name and Grades Structure; ProgramProgram, DataData

Slide 23 Operators Priority OperatorSame Priority Rule (),postfix++/--,[],.,-> Left to right Unary +/-, prefix++/--, !, ~,&, *Right to left *, /, %Left to right +, -Left to right >Left to right, =Left to right ==, !=Left to right

Slide 24 Operators Priority (Cont.) OperatorSame Priority Rule & ^ | &&Left to right ||Left to right ?:Right to left,Left to right

Slide 25 Union Create a new type (union union_name) by union sets of different data types Declare as union union_name { type1 variable1; …; };

Slide 26 Union (Cont.) Example: union number { long i; float f;}; typedef union number number; number number1, number2; number1.i=100; number2.f=-1.23; printf(“%d%f\n”, number1.i, number1.f); printf(“%d%f\n”, number2.i, number2.f);

Slide 27 Example Helpful Code

Slide 28 Structure with Bit Fields Purpose: reduce space Declare structure data types using bits fields as struct structure_name { unsigned field1: number of bits, field2: number of bits, :0, // align to next word …; }; typedef struct structure_name structure_type; structure_type variable_list;

Slide 29 Structure with Bit Fields (Cont.) Example: Create a small_number that has 7 bits of signed integer or float struct small_number { unsigned int_sign: 1, // 0: positive, 1: negative using 2s complement i : 6, :0, // align to next word float_sign: 1, f : 6; // don’t worry align at the end }; typedef struct small_number small_number; small_number s_number1;

Slide 30 Structure with Bit Fields (Cont.) Example: (Cont.) // assign 23 to snumber1 snumber1.int_sign=0; snumber1.i=23;

Slide 31 Data Structure - stack Stack: insert (push) and delete (pop) at the same place (top).

Slide 32 Example 1- stack Write a program that implements a stack of characters using an array. typedef struct stack { char s[STACKSIZE]; int top; } stack;

Slide 33 Example 1– stack (Cont.) void clear_stack (stack *stk) { stk->top=-1; }; void push(char c, stack *stk) { stk->top++; stk->s[stk->top]=c; }

Slide 34 Example 1– stack (Cont.) char top (const stack *stk) { return (stk->s[stk->top]); }; char pop (stack *stk) { return (stk->s[stk->top--]); }

Slide 35 Example 1– stack (Cont.) int is_full (const stack *stk) { return ((int) (stk->top == STACKSIZE-1)); }; int is_empty (const stack *stk) { return ((int) (stk->top == -1)); };

Slide 36 Example 2- stack Write a program that implements a stack of integers using a linked list. typedef struct node { int info; struct node *next; } node; typedef struct stack { node * head; } stack;;

Slide 37 Example 2– stack (Cont.) void clear_stack(stack *stk) { stk->head=NULL; }

Slide 38 Example 2– stack (Cont.) // insert item to head, delete from head void push (int item, stack *stk) { node *newnode; newnode = malloc(sizeof(node)); // dynamically create a new node if (!newnode) printf("No memory is available.\n"); else { newnode->info= item; newnode->next= stk->head; stk->head=newnode; } // else }

Slide 39 Example 2– stack (Cont.) int top (const stack *stk) { return (stk->head->info); }

Slide 40 Example 2– stack (Cont.) int pop (stack *stk) { int item; node *deletednode; deletednode=stk->head; item=deletednode->info; stk->head=deletednode->next; free(deletednode); return item; }

Slide 41 Example 2– stack (Cont.) int isempty (stack *stk) { return (stk->head == NULL); }

Slide 42 Example 2– stack (Cont.) void output (stack stk) { printf (" ”); Printf(“All items in the stack: \n"); for (;!isempty(&stk);) { printf("%d\n", top(&stk)); stk.head=(stk.head)->next; }

Slide 43 Example 2– stack (Cont.) Helpful Code Data

Slide 44 Data Structure - Queue Insert (enqueue) at the tail and Delete (dequeue) at the head.

Slide 45 Example - Queue Write a program that implements a queue of integers using a linked list. struct node { int info; struct node *next; }; typedef struct node node; node *head=NULL, *tail=NULL; // initialize

Slide 46 Example – Queue (Cont.) int isempty (node * head) { return (head == NULL); }

Slide 47 Example – Queue (Cont.) // insert item to tail, delete from head void enqueue (node **ptrhead, node **ptrtail, int item) { node *newnode; // dynamically create a new node newnode = malloc(sizeof(node)); if (!newnode) printf("No memory is available.\n");

Slide 48 Example – Queue (Cont.) // insert item to tail, delete from head (Cont.) else { newnode->info= item; newnode->next=NULL; if (isempty(*ptrhead)) // if (!(*ptrhead)) means head is equal to NULL *ptrhead=newnode; else (*ptrtail)->next=newnode; *ptrtail=newnode; } // else } // enqueue

Slide 49 Example – Queue (Cont.) // delete from head and return info int dequeue (node **ptrhead, node **ptrtail) { int item; node *deletednode; deletednode=*ptrhead; item=deletednode->info; *ptrhead=deletednode->next; if (isempty(*ptrhead)) *ptrtail=NULL; free(deletednode); return item; }

Slide 50 Example – Queue (Cont.) void output (node *head) { printf (" ”); printf(“All items in the queue: \n"); for (;!isempty(head);) // for (;head != NULL;) { printf("%d\n", head->info); head=head->next; }

Slide 51 Example – Queue (Cont.) Program (node is int) Code Data Program (node is a structure) Code Data

Slide 52 Data Structure – Binary Tree Each (parent) node has at most 2 children Binary search tree: right child node value > parent node value > left child value

Slide 53 Example – Binary search tree Write a program that implements a binary search tree of integers using a linked list. typedef struct node { struct node *left; int info; struct node *right; } node;

Slide 54 Example – Binary search tree (Cont.) typedef struct tree { node * root; } tree;

Slide 55 Example – Binary search tree (Cont.) void clear_tree(tree *bst) { bst->root=NULL; }

Slide 56 Example – Binary search tree (Cont.) void insert (int item, tree *bst) { node *newnode; if (bst->root == NULL) // base case { newnode = malloc(sizeof(node)); // dynamically create a new node if (newnode == NULL) printf("No memory is available.\n"); else { newnode->info= item; newnode->left= NULL; newnode->right= NULL; bst->root=newnode; printf("%d\n", bst->root->info); }

Slide 57 Example – Binary search tree (Cont.) Else // inductive case { if (item> bst->root->info) bst->root=bst->root->right; else bst->root=bst->root->left; insert(item, bst); } } // insert

Slide 58 Example – Binary search tree (Cont.) Helpful Code Data

Slide 59 Practice Given struct student { char lastname[15]; long studentid; char grade; }; struct student tmp, *p=&tmp; tmp.grade='A'; tmp.lastname="Casanova"; tmp.studentid=910017;

Slide 60 Practice (Cont.) Find the values of the following table: Expression Value ________ _____ tmp.grade tmp.lastname (*p).studentid *p->lastname+1 *(p->lastname+2)

Slide 61 Practice (Cont.) Find the values of the following table: Expression Value ________ _____ tmp.grade ‘A’ tmp.lastname “Casanova” (*p).studentid *p->lastname+1 ‘D’ *(p->lastname+2) ‘s’

Slide 62 References Deitel & Deitel: C How to Program, 4th ed., Chapter 10 & 12, Prentice Hall