You are on page 1of 380
Se \ {SS Ak . As per the New Revised Syllabus (REV- 2019 ‘C’ Scheme) of Mumbai University w.e.f. academic year 2020-21 Data Structure (Code : CSC303) Semester III Computer Engineering / Computer Science and Engineering / Artificial Intelligence & Data Science / Machine Learning / Cyber Security / Internet of Things (IoT) / Data Engineering / Data Science / Internet of Things and Cyber Security Including Block Chain Technology / Computer Science Design Dilip Kumar Sultania Se TechKnowledge ¥ : Publications ‘olved Latest University Question Papers. Uws DATA STRUCTURE (Code : CSC303) Computer Engineering / Computer Science and Engineering Artificial Intelligence and Data Science / Machine Learning Cyber Security / Internet of Things (IOT) / Data Engineering / Data Science Internet of Things and Cyber Security Including Block Chain Technology / Computer science Design Strictly as per the New Revised Syllabus (Rev ~ 2019 ‘C’ Scheme) of Mumbai University w.e.f. academic year 2020-2021 (As per Choice Based Dilip Kumar Sultania B.Tech.(hons.) Computer Science and Engineering, LLT, Kharagpur. SF TechKnowledge = ‘ Publications | MO146C Price ¢485/- IMA DATA STRUCTURE (Code : CSC303) Dilip Kumar. ‘Sultania (Semester 1M - Computer Engineer ‘nee / Machine Learn Internetof Things and ring / Computer Science and Engineering / Artificial Intelligence and Data ning / yber Security / Internet of Things (I0T) / Data Engineering / Data Science Qvber Security Including Block Chain Technology, Computer science Design MU) Copyright © by Author, AU rights reserved. No part of this publication may be reproduced, copied, or stored ing Netrieval system, distributed or transmitted in any form or by any means, including photocopy, recording, op other electronic or mechanical methods, without the prior written permission of the publisher. This book is sold subject to the condition that it shall not, by the way of trade or otherwise, be lent, resold, hired ‘out, or othenvise circulated without the publisher’s prior written consent in any form of binding or cover other than which i is published and without a similar condition including this condition being imposed on the subsequent purchaser and without limiting the rights under copyright reserved above. First Printed inIndia July 2007 (For Pune University) First Edition : August 2020 (Rev - 2019 'C’ Scheme) Second Revised Edition: July 2021 Third Revised Edition: July 2022 This edition is for sale in India, Bangladesh, Bhutan, Maldives, Nepal, Pakistan, Sri Lanka and designated countries in South-East Asia, Sale and purchase of this book outside of these countries is unauthorized by the publisher. ISBN: — 978-93-89889-98-7 a eld TECHKNOWLEDGE PUBLICATIONS i @ ork fs 37/2, Ashtavinayak Industrial Estate, B/S, First floor, Maniratna Complex, Taware Colony: Near Pari Company, Aranyeshwar Corner, Pune - 411 009. Narhe, Pune, Maharashtra State, India, Maharashtra State, India Pune- 411041 Ph:91-20-24221234, 91-20-24225678. Email : info@techknowledgebooks.com, Website : www.techknowledgebooks.com Subject Code: CSC303 BookCode : MO146C We dedicate this Publication soulfully and wholeheartedly, in loving memory of our beloved founder director, Late Shri. Pradeepji Lalchandji Lunawat, who will always be an inspiration, a positive force and strong support behind us. “My work is my prayer to God” ~ Lt. Shri. Pradeepji L. Lunawat Soulful Tribute and Gratitude for all Your Sacrifices, Hardwork and 40 years of Strong Vision... My Dear Students, e out with this book on “Data Structure” for you. The topics Lam extremely happy ¢o com equence to ensure smooth flow of the within the chapters have been arranged in a proper s subject. ‘A large number of programs and functions have been included. So, that this book will cater for all your needs. I present this book in the loving memory of Late Shri. Pradeepjt Lunawat, our source of inspiration and a strong foundation of “TechKnowledge Publications”. He will always be remembered in our heart and motivate us to achieve our milestone. 1am thankful to Shri. J. S. Katre, Shri, Shital Bhandari, Shri. Arunoday Kumar and Shri. Chandroday Kumar for the encouragement and support that they have extended. I am also thankful to Seema Lunawat for technology enhanced reading, E-books support and the staff members of TechKnowledge Publications and others for their efforts to make this book as good as it is. | have jointly made every possible efforts to eliminate all the errors in this book. However if ‘you find any, please let me know, because that will help me to improve further. 1.am also thankful to my family members and friends for patience and encouragement. - Dilip Kumar Sultania Mumbai University Revised syllabus (Rev-2019 'C’ Scheme) from Academic Year 2020-21 Course Code Course Namo csc303 Data Structure Prerequisite: C Programming Course Objectives: To understand the need and significance of Data structures as a computer Professional. To teach concept and implementation of linear and Nonlinear data structures. To analyze various data structures and select the appropriate one to solve a specific real-world problem. To introduce various techniques for representation of the data in the real world. To teach various searching techniques. Course Outcomes: Students will be able to implement Linear and Non-Linear data structures. Students will be able to handle various operations like searching, insertion, deletion and traversals on various data structures. Students will be able to explain various data structures, related terminologies and its types. Students will be able to choose appropriate data structure and apply it to solve problems in various domains. Students will be able to analyze and Implement appropriate searching techniques for a given problem. Students will be able to demonstrate the ability to analyze, design, apply and use data structures to solve engineering problems and evaluate their solutions. Detailed Content Introduction to Data Structures Introduction to Data Structures, Concept of ADT, ‘Types of Data Structures-Linear and Nonlinear, Operations on Data Structures. (Refer Chapter 1) Stack and Queues Introduction, ADT of Stack, Operations on Stack, Array Implementation of Stack, Applications of Stack-Well form-ness of Parenthesis, Infix to Postfix Conversion and Postfix Evaluation, Recursion. Introduction, ADT of Queue, Operations on Queue, Array Implementation of Queue, Types of Queue-Circular Queue, Priority Queue, Introduction of Double Ended Queue, Applications of Queue, (Refer Chapter 2) Linked List Introduction, Representation of Linked List, Linked List v/s Array, Types of Linked List - Singly Linked List, Circular Linked List, Doubly Linked List, Operations on Singly Linked List and Doubly Linked List, Stack and Queue using Singly Linked List, Singly Linked List Application-Polynomial Representation and Addition, (Refer Chapter 3) Trees Introduction, Tree Terminologies, Binary Tree, Bina! Binary Tree, Binary Tree Traversals, Search Tree, ry Tree Representation, Types of Binary Search Tree, Operations on Binary Applications of Binary Tree-Expression Tree, Search Trees-AVL, rotations in AVL Tree, Tree, B+ Tree, Huffman Encoding, operations on AVL Tree, Introduction of B (Refer Chapter 4) Graphs Introduction, Graph Terminologies, Re; Depth First Search (DFS) and Bread Topological Sorting. Presentation of Graph, Graph Traversals- th First Search (BFS), Graph Application- (Refer Chapter 5) Sorting and Searching Linear Search, Binary Search, Hashing-Concept, Hash Functions, Techniques, Collision resolution (Refer Chapter 6) Mumbai University Revised syllabus (Rev-2019 ‘C’ Scheme) from Academic Year 2020-21 Lab Code Lab Name Credit CsL301 Data Structures Lab on Proroqulsite: C Programming Language Lab oO! 1 2 3 4, bjectives: ‘To implement basic data structures such as arrays, linked lists, stacks and queues Solve problem involving graphs and trees To develop application using data structure algorithms ‘Compute the complexity of various algorithms. Lab Outcomes: 1 3 4 Students will be able to implement linear data structures and be able to handle operations like insertion, deletion, searching and traversing on them. ‘Students will be able to implement nonlinear data structures and be able to handle operations like insertion, deletion, searching and traversing on them Students will be able to choose appropriate data structure and apply it in various problems Students will be able to select appropriate searching techniques for given problems. Suggested Experiments: + Students are required to complete atleast 10 experiments. ‘Star (*) marked experiments are compulsory. oo 2 3 4 5* 6 7 et or 10 Implement Stack ADT using array. Convert an Infix expression to Postfix expression using stack ADT. Evaluate Postfix Expression using Stack ADT. Applications of Stack ADT. Implement Linear Queue ADT using array. Implement Circular Queue ADT using array. Implement Priority Queue ADT using array. Implement Singly Linked List ADT. Implement Circular Linked List ADT. Implement Doubly Linked List ADT. Implement Stack / Linear Queue ADT using Linked List. Implement Binary Search Tree ADT using Linked List. Implement Graph Traversal techniques : a) Depth First Search b) Breadth First Search Applications of Binary Search Technique. $F Data Structure (MU-Com EE Chapter 1; Introduction to Data Structures_1-1 to 1-27 ‘Syllabus ; Introduction to Data Structures, Concopt of ADT, Types of Data Structures-Linear and Nonlinoar, Operations on Data Structures. 14 Data... 1.4.1 Data Types... 4.1.2 Abstract Data Types (ADT)... 1.4.3 Data Object . 1.2 Data Structures. 1.2.1 Types of Data Structures. = Wollformness of Paranthesis, ‘and Postiix Evaluation, Recursion. Queue, Operations Queue, Typos of Quoue-Circular Queue, Introduction of Double Ended Ques, Applications of Tablo of Contonts Finding whothor a given Squaro Mates 'o ‘Symmoteical pennies 125 1.114 Multiplication of Two Matrices Ary » n and By yp ner 126 Chaptor2:_ Stack and Quoues 2-1 to 2-63 Syllabue : Inlroduction, ADT of Stack, Oporations o Stack, Array Implomontation of Stack, Applications of Stack Infix to Postfix Conversion | Introduction, ADT of ‘on Quoue, Array Implementation of Priority Queus, 4.2.1(A) Primitive and Non-Primitive Queue. 4.2.1(B) Linear and Non-Linear... 24 Introduction 1.2.1(0) Static and Dynami 22 Operations on Stacks. so 1.3. Relationship among Data Object, Data Type, 23 Array Representation. 2a Data Structure and Data Representation... eat ‘6 Functor for Pri 1.3.1 Operations on Data Structure ona Stack.. suena BB 1.4 Algorithm Analysis... 2.3.2 Program Showing Stack Operations 144 nea oe 23,3 Well-Formedness of Parenthesis.. 1.4.2 Measurement of Growth Rate Ed Operations on Stack Conelceseg (Asymptotic Growth Rate 17 ° 1.4.2(A) Asymptotic Consideration | eens 1.4.2(8) Constant Factor in Complexity Measure. 1-7 | 24 Applications of Stack.. 1.43 Notation ©: (Pronounced as Big-Oh), 24d Expression Representation sh (0(02) is Pronounced as Big-Oh of n? ) 4.9 | 242 Evaluation of a Postfix Expression 1.4.4 Best Case, Worst Case and the Average using a Stack. se Case Behaviour. 24.3 Conversion of an Expression from Infix 1.5 Introduction to Arrays fe Sotier “ 242 1.8 Representation and Analysis, 25 Expression Conversion (A Fast Meth0d) nn. 2-22 1.7 One-Dimensional Arrays 2.5.1 Infix to Postfix... 222 18 Operations with Arrays. 25.2 Algorithm to Check Well-Formedness of 1.81 Deletion. Parenthesi... Toone 2.6 Introduction to RECURSION vss 1.83 Search. 27 Converting a Recursive Function to 1.24 — Merging of Sorted Arraye.. an Equivalent C-Function 49 Two-Dimensional aye 2.7.1 Finding Factorial of an integer Number tos 27.2 Finding nth Term of Fibonacci 192 ‘Sequence Recursive Definition .. 110 MulicDimensional Arrays. 2.73 Finding GCD of given Numbers mak iat 3 Array ; _ coaten of x? using Recursion. it 0 2-D Matiicos 27-5 Calelaton of Sum a Dig. < 8 of Square Matsix.. Examples of Recursion ., We_data structure (wu-Comp,) 2 Table of Contents 2.8.1 Finding Sum of the Elements Stored 3.1 Representation and Implementation of inan Array. : 229 Singly Linked USt9.snnnnnrnnnmnnen A 2.88)‘ Function for ing Su of tho 3.1.1 Comparison between Array and Elements of an Array.. sennansesee Linked Lists 2.8.2 Finding Length of a String 3.1.2 Representation. BA 2.8.3 Reversinga String....... o 3.1.3 Implementation... 3-2 2.8.4 Searching a Number in aN AMY nnn 3.1.4 Types of Linked List 33 2.8.5 Finding Largest Element in an Array nen 8.1.4(A) Singly Linked List... 33 2.8.6 — Binary Search, 3.1.4(8) Doubly Linked List 3-3 2.8.7 Tower of Hanoi Problem, »2-31 | 3,1,4(C) A Circular Linked List. 33 2.9 Solved Examples.. Differences between Singly Linked 2.10 Removal of Recursion List and Doubly Linked List 211 Tall ReCUtBioN non Basic Linked List Operations .wvuesonenoonn So 2.12 Array and Linked Representation and Creating a Linked List. Implementation of Queues Traversing a Linked List. Pees aera Counting Number of Nodes in @ 212.2 Application of Queues... Linked List through Count Function... 2.123 Array Representation and implementation Printing a List through Print Function . Of QUEUES. 2.99 : 32.5 _ Inserting an tem. 2:43 Operations on Queue... Ba) eee aoe re ear fing an Item a 2.43.4 ecina ‘on Queue implemented” Dae 3.2.5(8) Inserting a Data‘ ata given Location ‘LOC’ in a Sie eeaaerenee nd ; Linked List, Referenced by ‘head. 28 2.14.1 Queue using a Circular Array Bete ee eee it 2.14.(A) Implementation of a Circular ses aa reer 2 Movement Inside a Linear Array. 2.18 Applications of Queue eee aie 2.18.1 Categorzing Data, 4.2.6(A) Deon ofthe Last Node o Linked Lis 2152 Job Scheduling, 3.2.6(B) Deletion of a Node at Location ‘LOC 2.183 Queue Simulation ftom « Linked Lit 23611) Paany Giea 2440) Dae Liked Lis, ference byte 2.16.1 Implementation of Priority Queues ... Rointer Heed : 2.16.1(A) Implementation of a Priorty Queue caer aa using a Circular Array : 3.2.8 Inversion of Linked Lis 2.162 Dequeues... 82.9 Searching a Data’ in a Linked List, 2.16.3 Implementation of Dequeue using a Circular, Referenced by the Pointer Head... 3415 ae 3.2.10 Searching an Element xin a Sorted Linked List. Famuess 2.11. New Linea Linked List by Selecting Altemate Element 3.2.12 Handling of Records through Linked List. Chapter :_Linked List 34 to.3-59 3.2.13 Merging of Sortad Linked Lists. Syllabus + Introduction, Representation of Linked List, || 3.2.14 Spliting a Linked List atthe Middle pt Linked List vis Array, Types of Linked List - Singly Linked ‘and Merge with Second Half as First Half......3-18- List, Circular Linked List, Doubly Linked List, Operations on |] 3.2.18 Removing Duplicate Elements from a Singly Linked List and Doubly Linked List, Stack and Linked List... Queue using Singly Linked List, Singly Linked List |] 3.3 Circular Linked List. plication Polynomial Representation and Addition, 3.3.1 Application of Clear Lnked Lit. Data Structure (MU-Comp,) 3.4 Doubly Linked List 3.4.1 Creation of a Doubly Linked List. 3.4.2 Deletion of a Node... 3.5 Doubly Linked Circular List. 3.6 Applications of Linked Lists... 3.6.1 Polynomials as Linked Lists... 3.6.2 Addition of Two Polynomials... 3:7 Linked Representation of a Stack. 3.7.1 Functions for Stack Operation 3.8 Linked Representation of a Queve.... 3.8.1 Comparison between Array Representation ‘and the Linked Representation of a Queue.....3-50 3.8.2 Operations on Queue Implemented using Linked Structure... 851 3.9 Queue using a Circular Linked List. 3-55 3.9.1. Implementation ofa Priority Queue using a Linked List. 3-58 a 4-1 to 4-102 Chapter4: Trees Syllabus : Introduction, Tree Terminologies, Binary Tree, Binary Tree Representation, Types of Binary Tree, Binary Tree Traversals, Binary Search Tree, Operations on Binary Search Tree, Applications of Binary Tree-Expression Tree, Huffman Encoding, Search Trees-AVL, rotations in AVL Tree, operations on AVL Tree, Introduction of B Tree, B+ Tree 4.1 Basic Terminology. 4.1.4 Introduction... 44.2 Basic Terms 42 Binary Tree.. 43 Representation of a Binary Tree using an Array,.4-2 4.4 Linked Representation of a Binary Tree. 4.4.1 Program for Creation of a Sample Binary Tree... - 4.42 ‘C’ Function for Creation of a Binary Tree . 45 AGeneral Tree 4.5.1 Node Declaration for a Tree. 4.8 Types of Binary Tree 4.6.1 Full Binary Tree... 4.62 Complete Binary Tree, 4.63 Skewed Binary Tree 4.64 Strictly Binary Tree. 465 Extended Binary Tree (2-Tree)..., Tabla of Contonts 4.7 Binary Troo Travorsal.. 4.7.4 Proorder Travorsal (Recursive) 4.7.4(A) ‘C! Function for Proordor Traversal Inordor Traversal (Recursive)... AT2 4.7.2(A) ‘C! Function for Inordor Traversal 4.7.3 Postorder Traversal (Recursive) 4-19 4,7.3(A) ‘C' Funetion for Postordor Traversal. 410 4.7.4 Non-Rooursive Proordor Traversal 4-10 - 7 ive (A) 'C' Function for Non-Recursl 474M) ae Fedor of Tro Along with tho ADT Stack ...411 4.7.5 Non-Recursive Inordar Traversal ..-. 442 4.7.5(A) ‘C' Function for Non-Recursive Inorder Traversal of a Binary T1200 At2 4.7.6 Non-Recursive Postorder Traversal nner AA2 4.7.6(A) ‘C! Function for Non-Recursive Postorder Traversal... 4-146 47.7 Tree Traversal Examples 48 Basic Tree Operations. . 4.8.1 ‘C’ Function for Counting of Nodes in a Tree ....4-18 48.2 Function for Counting of Leaf Nodes in a Tree (Recursive) .......... 4.8.3 ‘C’ Function for Counting of Nodes of Degree 1 (Recursive)... 419 4.8.4 'C’ Function for Counting of Nodes of Degree 2 (Recursive) soteunenmennnene GD 4.8.5 — 'C’ Function to Create an Exact Copy of a Tree (Recursive)... 419 48.6 — 'C’ Function for Checking Equivalence of ‘Two Binary Trees...... 4.8.7 ‘C' Funetion for Finding Height of a Tree (RECUESIVE).. ure sented 2D 48.8 — ‘C’ Function for Swapping of Left and Right Children of Every Node (Mirror) .. 4.8.9 — Finding Width of a Tree 4.8.10 Function to List the DATA Fields of the Node of a Binary Tree T by Level. Within Lovels Nodes are Listed Left to Right. 4.8.11 Non-Recursive Algorithm for Height of a Binary Tree... iss ad 4.8.11(A) 'C' Function for Height of a Troe (Non-RECUTSIVE) ose... 42 4.9 Creation of a Binary Tree from Traversal Sequence. Ae 494 Creation of Binary Tree from Preorder and Inorder Traversal... 4s Creation of Tree from Postorder and Inorder Traversal. 410 440.4 4102 4.10.2(A) Initialize Operation. 4,10.2(8) Find Operation. : 4.10.2(C) Make Empty Operation. 4,10.2(D) _ Insert Operation. 4.10.2(E) Example on Creation of a BST... 4.10.2(F) 4.10.26) 4.10.2(H) 4.10.2(0) 4.10.3 an 4414 4at2 4118 ana 4115 4.11.5(A) Rotate Let 4.11.5(8) Rotate Right 4.11.5(C) Single Rotation and Double Rotation Examples on Tree Creation from Travorsal SeQUENCE sen ae Binary Search Ti (BST) Definition Operations on a Binary Search Treo. Find Max... Program for Various Operations on BST. AVL Trees. Height Balanced Tree. Balance Factor... Structure of a Node in AVL Tre °C’ Function for Finding the Balance Factor of a Node. Insertion of a Node into an AVL Tree... 4.11.5(D) °C’ Function for Insertion of an Element 4.11.5(E) 4.11.5(F) _‘C’ Function to Rotate Right. 4.11.5(G) _‘C’ Function to Rotate Lett. 4.11.5(H) 4.11.5()) 4.11.5(8) _ ‘C’ Funetion for LR. 4.11.5(K) _‘C’ Function for AL... 442 4424 4.122 4.123 412.4 4.13 4.48.1 into an AVL Tree Function to Find Height of AVL Tree Function for AR. ‘'C! Function for LL Application of Tre@8 0. Expression TI@€S..nnnnesnnn Program on Expression Tree from Posttix Expression. Conversion of an Expression into Binary Tree Construction of an Expression Tree from infix Expression.. Hutfman Algorithm, Huffman Codes. Table of Contonts 4.19.2 Reprosantation of Binary Codes as a Binary Troe, rennin TR 4.43.3 Hutfman’s Algorithm... avery 4.49.4 Program for Huffman Troe eons TT 444 B-Troes : : 478 4.14.1 Insertion of a Key into a B-tre8... 479 4.44.2. Deleting a Value from @ B-tr88 4-05 4.14.3 B-tree as an ADT. 4-89 418 Be Trees. eee renee OS 446 Splay T2... oe 497 4.16.1. Bottom up Splaying .. 497 4.16.2 Top Down Splaying 1. 4-99 4.47 Tie Indexing . 4-101 447.41 Compact Tre... 102 Module 5, Chapter 5 :_Graphs 5:1 to 5-26 Syllabus Introduction, Graph Terminologies, Representation of graph, Graph Traversals ~ Depth First Search (OFS) and Breadth First Search (BFS), Graph Application - Topological Sorting. 5.1 Terminology and Representation B.A1 Definition 5.4.2 Undirected Graph.. 54.3 Directed Graph... 5.1.4 AComplete Graph.. 5.1.5 Weighted Graph. 5.1.6 Adjacent Nodes. SAT Path. 518 Cyce.... - 5.1.9 Connected Graph. 5.1.10. Subgraph. 5.1.11 Component. 5.1.12 Degree of a Vertex. 5.1.13 Self Edges or Self Loops.. 5.1.14 Multigraph ... BANE Te onnnn 5.1.16 Spanning Tress... 5.1.17 Minimal Spanning Tree 5.2 Representation of Graphs... 52.1 Adjacency Matrix... 52.2 Adjacency List. 523 _ Path Matrix Table of Contents xz Data Structure (MU-Comp,) 5 _ 53 Traversal of Graphs... 6.8.3(C) Average-Case Analysis G25 5.3.1. Depth First Search (DFS). . G04 Role of Pivot in Efficiency of Quick Sor....6.25 5.3.1(A) Algorithm for Depth First Search (Recursive). 6.9 Two-Way Merge Sort... 628 5.3.1(B) Non-Recursive DFS Traversal. 6.9.1 Merging « 820 5.3.2 Breadth First Search(BFS) 6.9.2 Analysis of Merge Sor. 682 5:3.2(A) Algorithm for BFS... 683 Non-ecursve Merge Sort ° 5.4 Topological Sorting. 6.10 Comparison of plea i: ae 5.4.1 Program for Topological Sorting... on aes oe arals of Sorting Algorthm. 6.54 6.12 Extemal Vs Internal Sorting. 6.19 Hash Tables shing ?.. Sep e SetegendSeteg EEE co Strr Syllabus : Linear Search, Binary Search, Hashing: |] 6.13,2(A) Open Hashing Data Structure Concept, Hash Functions, Colson resolution Techniques. |] 19,2(B) Closed Hashing Data Structure... 61 Searching... 6.133 Hashing Functions 62 Sequental Search 6.13.3{A) Characteristics of a Good Hash Function.....6-37 6.2.1 Sequential Search on a Sorted Array: 6.13.3(6) _Division-Method ... 63 Binary Search 6.13:3(C) Midsquare Methods... 64 Sorting.. 6.13.3(0) Folding Method 64.1 Sort Stabil 6.13.3(E) Digit Analysis. GAR ‘port Eticiony. 6.13.3(F) Length Dependent Method. 645 passes. 6.13.3(G) Algebraic Coding... 65 _Insetion Sor. — . ; 6.13.3(H) Multiplicative Hashing «nun 6.5.1 Sorting an Array of Strings using ee ee onc ee iohten Gor. olution Strategies 65.2 Sorting an Array of Records on the ae oer) ivi ney using beaten Son 6.13.4(A) Separate Chaining. 6.6 Bubble Sort. 6.13.4(B) Open Addressing 67 election Sort. 6.13.4(C) Primary Clustering. 68 Quick Sort + Lab Experiments... : 6.8.1 Pickinga Prot. + Appendix A: Solved University Question 6.82 Partitioning nu. Papers of Dec. 2017, May 2018 6.8.3 Running Time of Quick Sort. and Deo, 2018. Art toa? 6.8.9(A) Worst-Case Analysis, 6.8.5(8) Best-Case Analysis . * Appendix B: Solved University Question Papers of May 2019 and Dec. 2019 Introduction to Data Structures svlebua Introduction to Data Structures, Concept of ADT, Types of Data Structures-Linear and Nonlinear, Operations on Data Structures. 1.1 Data _ Dataisa collection of numbers, alphabets and symbols, combined to represent information. = A computer takes raw data as input and after processing of data it produces refined data as output. We might say that computer science is the study of data, = Atomic data are non-decomposable entity. For example, an integer value 523 or a character value ‘K’ cannot be further divided. If we further divide the value 523 in three digits ‘S', ‘2’ and ‘3’ then the ‘meaning may be lost. — Composite data : itis a composition of several atomic data and hence it can be further divided into atomic data. Composto dora Cie ta xD Gor Cad sla Fig. 1.1.4 For example, date of birth (say 15/3/1984) can be separated into three atomic values. First one gives the day of the month, second one gives the month and the last one is the year. 1.1.4. Data Types ~ A data type is a term which refers to the kind of data that variables may hold in a programming language. Example : int x ; {x can hold, integer type data] — Every programming language has a method for declaring a set of variable of a particular type. = Avvalue stored in a variable cannot be interpreted properly without knowing its type. A byte of information stored in computer memory may represent an integer value, a character value, a BCD (Binary Coded Decimal) value or a Boolean value. Therefore, it Is necessary that the value stored in memory must be treated as of a particular type and interpreted accordingly. 1.1.2. Abstract Data Types (ADT) IQ. Define ADT with an example. . _(Dec. 13, May 16, Dec. 17, 3 Marks), The concept of abstraction is commonly found in computer science. A big program is never written as a ‘monolithic piece of program, instead itis broken down in smaller modules (may be called a function or procedure) independently. and each module is developed When the program is hierarchical organized as shown In the Fig. 1.1.2, then the “main program” utilizes services at the functions appearing at level 1. Similarly, a function written at level 1 utilizes services of functions written at level 2. Main program uses the services of the next level function without knowing their implementation details. to Data Structures Introduction 1 Hata Structure (MU-Com = ‘The Abstract Data Type “ARF! sy memory Thus a level of abstraction Is created. When an ‘our concern Is abstraction is created at any level, limited to “what it can do” and not “how itis done”. Flg, 1.1.2 : Hlerarchleal organized program Abstraction in case of data ‘Abstraction for primitive types (char, int, float) is provided by the compile. For example, we use integer tYPe data and also, perform various operations on them without knowing them : (1). Representation (2). How various operations are performed on them? Example = intx,y.25 x= 13; — Constant 13 is converted to 2's complement and then stored in x. Representation is handled by the compiler. aytz; = Meaning of the operation ‘+’ is defined by the Compiler and its implementation details remain hidden from the user. = Implementation details (representation) and how various operations are implemented remain hidden from the user. User is only concerned about, how to Use these operations. ~ Objects such as lists, sets and graphs along with associated operations, can be viewed as abstract data type. Integer, char, real are primitive data types and there are set of operations associated with them, ~ For the set ADT (Abstract Data Type), we might have operations like union, intersection, size and complement. Once the data type set is define, (representation and associated functions) ther "the hore n the DT set can be used in any application program, din consecutive Se! fan be thought of 25 2 268 Of pai, each index which is defined there 'f with that index. There are tig Ay’ data structure, These Arrays are store’ An array © locations. index and value. Fo! jater Is a value assoc ; operations permitted on ‘ARR ae two operations are retrieve and 210°" ‘ADT ARRAY can be det structure ARRAY (value, clared as below : index) declare CREATE( ) > array RETRIEVE(array, index) > value sToRE(array, index, value) — array The function CREATE( ) produces an empty array. The function RETRIEVE( ) takes as input an array and an index, and either returns the appropriate value or an error. The function STORE( ) is used to enter new index-value pairs. The Abstract Data Type “List” A list is @ sequence of 0 or more elements of a given type (element type, could be integer, float etc.) Such a list is often represented as : ay, 2 a Where; n = Number of elements in the list ith element of the list ~ When n=0, the list is empty having no element. ~ Each element, other than a, has a predecessor. ~ Each element, other than a,, has a successor. In order to form an ADT from the mathemat notation of a list, we must represent the list and define @ set of operations on objects of type List. Representation of a List Alist can be represented in typedef struct List { int datalso); int n; ” using a structure. + List; Bata Structure (MU-Comp,) 13 Introduction to Data Structures —Alist of maximum of 80 Integer type elements. 2. _IS2ERO{natno) -» boolean 3, sUCC{natno) ~>natno _ isthe actual numberof elements in the List. jabio) 4. ADD{natno, natno) + natno A set of representative operations on a List 5. EQUAL(natno, natno) -» boolean 4. tnsert( XP) Insert at position Pin List L. Poy This function returns the position of element X on List L 2. Locatel%L) + This function returns the element at position P on list L. 3, Retrleve(l, P) = 4, Delete(t,P) : Delete the element at position P of the List L MAKENULL(L) : Creates an empty List L. PrintList(L) : Print the elements of L in the order of occurrence. 1.1.3 Data Object = Data object refers to a set of variables used in 2 program. = It is 2 place where the data values can be stored, retrieved and manipulated. = Every data object is associated with data type (type of value that can be stored). — Accomplex object (structure type) can have a number of attributes. = Data object can also be viewed as a runtime instance of a data structure. 1.2 Data Structures Dee |_ What is data structure 7 (May 15,2 Marke) = Adata structure is merely an instance of an ADT. = An ADT or data structure is formally defined to be a triplet (D,F,A) where “D” stands for a set of Domains, “f” denotes the set of operations and “A” represents the axioms defining the functions in “F”. — An example of the data structure “Natural Number (NATNO)". Structure of Natural Number (NATNO) Operations 1. ZERO()— natno For allx, y € natno let, ISZERO(ZERO) is true. ADD(ZERO,Y) is ¥ EQUAL(x, ZERO), if SZERO(x) then true else false. = {natno, boolean} F = (ZERO, ISZERO, SUC, ADD, EQUAL} A= {Line no. 6 to 8 of the structure NATNO} 4.2.1 Types of Data Structures To Ez a jo. Ue Mrmr Explain different types of data structures with example. (May 14, May 17, May 18, § Marks) 4.2.1(A) Primitive and Non-Primitive Primitive ‘The integers, reals, logical data, character data, pointers and reference are primitive data structures. These data types are available in most programming languages as built in type. Data objects of primitive data types can be operated upon by machine level instructions. Non-Primitive These data structures are derived from primitive data structures, A set of homogeneous and heterogeneous data elements are stored together. Examples of Non-primitive data structures are Array, structure, union, linkedtlist, stack, queue, tree, and raph. ‘Some at the most commonly used operations that can be performed on data structures are shown in Fig, 1.2.1. \ Data Structure (MU-Comp.) 1.2.1(B) Linear and Non- la. Explain tinear and non-inear data structures, wih examples. (Dec. 19, May 15, Dee.16, Dec. 17, May 19,9 Marks) la. Ditterentiata linear and non-inear data structures wi? example, (Deo. 19, 4 Marks) Linear Elements are arranged in 2 Linear fashion {one dimension). All one-to-one relation can be handled through Linear data structures. Lists, stacks and queues are examples of linear data structure. (l) Representation of Linear data structures in an array Ataot comers é sak Frnt Rowe ! | ome Pop spale p= (I) Representation of Linear data structures through Linked structure Aust 0 coment Sees 7 Cop, oe - Be aT ei + Nor relations are ha! eve well non-inear data str Introduction to Data Structures wany to one or many to ‘all one to many, ™anY oo ndied through non-linear data structures vata element can have a number of Predecessor, ry data el i as successors. Tree 67a vuctures: jphs and tables are examples oy (a) Tree (b) Graph Ea e418 Lens ao. spe fat (c) Table Fig. 1.2.2 : Non- Linear data structures (2) Representation of the binary tree through linked structure we oe & tee" ee é STS. tTST2T3] oR ) Representation of the binary tree through an array Fig. 1.2.3; '9:12.3 : Representation of tree of Fig. 1.2.2(@) Trane ¥ Data Structure (MU-Comy 4.24(C)_ Static end Dynamic Static Memory Allocation In case of static data structure, memory for objects is allocated at the time of loading of the program. Amount of memory required is determined by the compiler during compilation. Example : int a[50}; ‘Memory for the array ‘a’ of 50 element will be allocated at the time of loading of the program, It may not always be possible to fix the size of the array in advance. ‘Amount of data to be handle is often determined by the user and not by the programmer. Our initial judgment of sie, if wrong, may cause failure of program (due to overflow) or wastage of memory space. = Static data structure causes under utilization of memory (in case of over allocation), — Static data structure may cause overflow {under allocation). = No reusability of allocated memory. — Difficult to guess the exact size of data at the time of writing of program. Dynamic In case of dynamic data structures, the memory space required by variables is calculated and allocated during ‘execution. Dynamic memory is managed in‘C’ through a set of library function. Allocating a block of memory in “C” “pir = (cast_type) malloc(byte_ sie) The “malloc( )” returns a pointer of (cast type) to an area of memory with size, (byte_size) Example : 1.3 Introduction to Data Structures Relationship among Data Object, Data Type, Data Structure and Data Representation A data type is a term which refers to the kind of data that variables may hold in a programming language. Every programming language has a method for declaring a set of variables ofa particular type. A value stored in a variable cannot be interpreted properly without knowing its type. A byte of information stored in computer memory may represent an integer value, a character value, 2 BCD value or a Boolean value. Therefore, it is necessary that the value stored in memory must be treated as of a particular type and interpreted accordingly. Data object refers to a set of variables used in a program. Every data object is associated with data type. A complex object can have a number of attributes. Data object can also be viewed as a runtime instance of a data structure. Every type of data is converted into a stream of bits before it is stored in memory. Integers are represented as a signed binary numbers. Floating point numbers are represented in IEEE format. A data structure is merely an instance of an ADT. In ‘Most cases, a data structure is defined using structure and associated functions are written. A proper selection of data structure will determine the efficiency of the associated functions. 1.3.1 Operations on Data Structure la. Cerca What are various operations possible on data structures? (Dec. 18, 5 Marks) x = (int *) malloc(100 * sizeof{in')) ; = A Linear data structure can be implemented either through static or dynamic data structures. Static data structured is preferred. — All Linked structures are preferably implemented through dynamic data structures. = Dynamic data structures provide flexibility in adding, deleting or rearranging data objects at run time, Additional space can be allocated at run time. — Unwanted space can be released at run time. It gives re-usability of memory space. Many operations are performed on a data structure, ‘Typical operations on a data structure are 1. Traversing 2, Searching 3. Inserting 4, Deleting 5. Sorting 6. Merging ‘Traversing a data structure is accessing each data and accessing only once. Searching is finding the location of a data in within the alven data structure, Frais ¥F bata structure (MU-Comp.) 3. Inserting is adding a new data In the data structure. 4, Deleting is removing a data from the data structure. 5. Sorting is arranging of data in some logical order. 6 Merging is combining of two similar data structures. 1.4 Algorithm Analysis Most often there are many algorithms for solving 3 problem. On what basis should we choose an algorithm ? There are often two contradictory goals. (Algorithm should be easy to understand, write and debug. Algorithm should make efficient use of computer resources like CPU, memory etc = When we write a program to be used a few times, goal) is most important. Cost of writing the program will have an upper hand over the cost of running the program, when the program is to be used many times, the cost of running the program and hence the goalli) should be given more weightage. — Analysing a program should quantify the requirement of computing resources during execution. Most important of these resources are computer time and memory. Analysis of algorithms focuses on computation of space and time complexity. = Space requirement means the space required to store input data either static or dynamic. Space required on top of the system stack to handle recursion/function Call should also be considered. Computing time, an algorithm might require for its execution, would normally depend on the size of the input. #include void main( ) { inti, 1, sum, x3 sum = 0; printf(“\n Enter number of data to be added”); scanf("Yed”, &u); seanf("9%d”, &x); 1-6 Introduction to Data Struct Space required to store the Space requirement 42424228 variables i, n, sum and [An integer requires 2 bytes of memory space.] Calculation of computation time Computation Statement IFrequency) time lsum=0 1 ty lprintf("\n Enter number off a data to be added”); lscanf("s6d", &n) 1 ts lror(i= 1 ;i alj + 1) { temp = o| Statements afl) = alj+4}; for interchange af} + 1]= temp; | of af and af +1) Solution For calculation of timing complexity, itis sufficient to express number of interchanges in terms of n(number of data). retum(A(n 1) + A(n 1} Solution : Recursion tree for n= 4 When the function called with the initial value of n= 4, it calls the same function recursively twice with n = 3 thus, fio) = 240-1) ifn>1 fo) = 1 imn<=1 (Best case) Since fin) = = 2-1 fia (a= 1)) = 28-1 A) =2"-1 = 00m, Data Structuro (MU-Comy Fig. Ex, 1.4.10 Worst Case and the Average Case Behaviour Many programs do not produce same timing 1.4.4 Best Case, complexity in every case, Consider the problem of searching an element in an array with 10 elements s][]s[2]1]23]6]7]36 Element 5 wil be found in one attempt Element 16 will equire 10 comparisons to locate Best case behaviour = 1 comparison (when the ‘element to be searched Is in the beginning) Worst case behaviour = n comparisons (where nis the numberof elements and the element tobe searched Is atthe end of the array) Average case behaviour be n/2 (from probability). umber of comparisons will Calculate the worst case time complexity of the following program (Function for binary search) : int binsearchiint a [) nt, int}, int x) (Inti; k= (+ pa while( <=) { Mx > alk) lek; ols (x < alk) ek-1; ise return(k); Example 1.4.11: k = (+ ya; return(- 1); } Solutlot 4 Introduction to Data S: inary search requires that elements are sorted in ascending order. {1s the starting index (le. 0), j is the index of the ‘element (n~ 1)- k gives the index of the centre element. 25 9 8 11 13 15 +— Element 0102 3 4 5 6 += Index i k i t t t =0, j=6 k=(0+6)/2=3 Element to be searched is x. Inside the while-loop, if the element x is found at the location k (centre), we return k. Inside the while-loop, if the element x is larger than the centre element; we select the second half of the array. Inside the while-loop, if the element x is smaller than the centre element; we select the first half of the array. 2 [sls] 2 [ulsl x First half | Second half | Centre i=6 element k=3 Element to be searched, x= 13, a1 | a3] a5 Second half of the element 156 'n order to calculate time complexity, binary search fr n elements must be expressed in terms of bina search of fewer numbers ( #include void main() { int a(3]=45, 4, 3}; tf("in a[0] , value=Ved : address=%u", al], S(O); printf("in a[1] , value=%d : address=9u", o[1], &a{))s print{("\n a[2] , value=9ed : address=%u", a[2], &al2)); getchQ; } Output ‘An integer requires 2 bytes of memory locations. Addresses displayed have a difference of 2 1.7 _ One-Dimensional Arrays Finclude #include void main) { int i, [50], sum, n, even, odd printf(\n Enter no. of elements :") cean{("%a, &n); // Reading values into Array print{("wn Enter the values :") for(i=0; i GhTTele repay #include VOSS ‘void main() Creation of space at location 2 Index of location 2 is 1 { he. loc=1 int [30], n, i b Mover [+ __1:n0, of elements sored jn array rn M8 tO ts rhe stars from bist location(index n~ 1) W_ata Structure (MU-Comp,) 115, Introduction to Data Structures ford = a=W > = lool; i Enter the element to ho inserted : 20 afi +1) = ali Enter the location 2 o_o psn) ‘Space Is ematod nt location 2 (Indox 1) eeLilsTele rsh] 9-8 after Insntion Data to be inserted = 20 ‘ray Program 1.8.2: Program for Insertion of an element at the specified location. #include #include void main() { int a(30},x. mi, loes ” x: element to be inserted n_:no. of elements in the array i: for scanning of the array loc : place where the new element is to be inserted print{('\n Enter no. of elements :"); seanf("od", &n /* read n elements in an array */ for printf("yn Enter the element to be inserted seanfi"Ged", &x): printf("\n Enter the location”) scanf("%ed", &loc); /* create space at the specified location */ for(i=n-1; i> =loc-1; i- -) afi+1]=ali}; atts afloc-I]=x; /* Element insented */ /* Printing of result */ . for(i=0; i #include for scanning of an array x-> no. of elements in the array ” print{("\n Enter no. of elements seant("%od", &n); /* Reading values into Array */ printi("in Enter the values :"); for(i=0; i #include void main() { int {30}, x, mi - for storing of data x: element to be searched n :no. of elements in the array i: scanning of the array " print{("\n Enter no. of element seanf("ed", &n); ge /* Reading values into Array */ print{("\n Enter the values :"); for // read the element to be searched. ate printf("\n Enter the elements to be searched"); scanf("Jod", &x); a /* search the element */ ‘0; // search starts from the location zero while(i #include void main() { int a[80], b[30), {30} i j,k, nl, n2; a nl : no, of elements in the array ‘a! n2 : no. of elements in the array 'b’ ah print{(\n Enter no. of elements in Ist array :"s seanf("%ed", &n1); for(i=0; i #include void main() Program 1.9.1: Program to show the use of two dimensional array. int a(1O][10}, m, n, i, js / physical size of the array is 10*10 whereas a specified size of the aray of the size m*n can be st * tored in array a ¥/ ™m : number of rows ‘n number of columns oy, Print(\n Enter the Tows and columns :' Techies Bata sirueture (MU-Comp) 419 Introduction to Data Structures scanf("Sed Sd", &m, &n); — Anested loop Is required to scan all elements of a two * Reading m*n elements */ dimensional array. Outer loop is for rows and the inner for(i=0: i Number of planes (from plate number 0 to m1) n> Number of rows in each plane (from row number Oton-1) Pp Number of columns in each plane (from column number 0 to p-1) Number of elements in each plane =n xP. Element afilLJIK), will be found in the it plane. s s “po faa Fig. 1.10.1 Offset of ih plane = ix size of plane =ixnxp Offset of j row ina plane = j x number of elements in a row = ixp Offset of k element in arow = k «+ aliTE{]0K will found at the address = Starting address ofthe array + (ix nx p +j X p+) x Size of each element 1.11. Application of Arrays 1.11.1 Addition of Two 2-D Matrices = Hfwe add two matrices an xq and bm 9 Producing Cm x n then (i, J element of the resultant matrix HIG) = ali}0) + BIG. - Two matrices can be added using the following program segment the array © i #include . void add(int{ ][10}, int{ ][10},int{}{10), int, int); void read(int{ }[10}, int, int); void print(int{ }[10}, int, int); void main() { int a{10}[10}, b(10}(10}, ef10)(10}, m, n; printf("\n Enter the size of matr scani"%ed%ed", &m, &n)s print{(\n Enter the elements of 1'st matrix"); ‘read(a, m,n); printf("\n Enter the elements of 2'nd matrix"); read(b, m, n); add(a,b, e, m,n)5 printf('\y I'st matrix is print(e, m,n}; printf("\n 2'nd matrix is Print(b, m, n); printf("\n result matrix print(c, m, n}s E void add(int x{ ][20}, int yf ][10}, int 2{J[10}, int m, int n) { int, is for(i=0; i j le, row index > column index (©) Upper triangle For any element ay, i ] for lower triangle. 5. Program segment for finding the sum of all elements of the upper triangle (Minus main diagonal) si #include void main() { int a[10][10), n, i,j, major, minor; printf(“\n Enter size of the matrix(n for n Xn) :”); scanf(“%d”, &n); printf(*\n Enter matrix data :"); for(i s i Sena 75 eae #include w 4 9652 Fata structure (MU-Comp) 1.11.3 Finding whether a given Square Matrix is Symmetrical ‘A square matrix is said to be symmetrical if the matrix ‘A= AT (AT = transpose of A) A square matrix is said to be symmetrical if for all ay lower triangle, a5 = a, Program 1.11.4: Write a program to print major and minor diagonal elements of square matrix. # include # include void main) { inta [10][20},n, i,j scanf("Sed", &afilf})s Print{(“\n Enter size of the matrix(n of nx result=symmetry(a, m); seanf(“%ed”, &n); if(result==0) print{(“\n Enter matrix data :”); print{(\n Not symmetrical"); #include int symmetry(int af J[L0}, int m); void main() { int a{10][10}, m, i, j, result; printf(\n Enter the size of matrix seanf("%ed, &m); /* Reading matrix elements */ printf("\n Enter the values :"); } j #include void read(int{ }(20}, int, int) ‘void print(int{ }{20), int, int); void multiply(int{ ][10}, im{ ][10}, im ][10}, int, int, int); void main() { int a{10}[20}, b{10}(20}, ef10){10}, m,n, ps /* first matrix of size m*n (3) second matrix of sizen*p —(b) resultant matrix of size m*p (c) “ printf("in Enter the size of I'st matrix scanf("%ed%d", &m, &n); printi("yiEnter no. of columns in the 2nd matrix"); scanf("Zed", &p); printf("1n Enter the data of 1'st matrix :"); read(a, m, n); printf("\n Enter the data of 2'nd matrix :"); read(b. n. p): multiply(a, b, e, m,n, p); printf(“\n Result is :”); print(c, m, p); + void read(int a[ }[10], int m, int n) { inti, for(i=0; i slit) keji printf“ largest of row Ged =e i afi}tk))s ooo Stac Mod: ule 2 k and Queues 2 U 2.2 1. 2. 3. 4 ‘Syllabus Introduction, ADT of Stack, Operations on Stack, Arra Wel-formness of Parenthesis, Infix to Postfix Conversion Queue, Operations on Queue, Array Implementation of Qt Introduction of Double Ended Queue, Applications of Queue. 1 Introduction Stack is a UFO (Last In First Out) structure. It is an ordered list of the same type of elements. A stack is 2 linear list where all insertions and deletions are permitted only at one end of the list. When elements are added to stack it grows at one end. Similarly, when elements are deleted from a stack, it shrinks at the same end, Fig. 2.1.1 shows expansion and shrinking of a stack. Initially stack is empty. shi sea [E 7 —e Lo 2 Fig. 2.1.1 : Insertion of 9,5,3 ina stack top o ope te Fig, 2.1.2 : Deletion of 3 elements from the stack ‘Avariable top, points to the top element of the list. Operations on Stacks Initialize() _: Make a stack empty Empty() + To determine if a stack is empty or not Full) 1 To determine if a stack is full or not Push( ) 1 Ifa stack is not full then push a new element at the top of the stack (similar to insert ina list) y Implementation of Stack, Applications of Stack ~ ‘and Postfix Evaluation, Recursion. Introduction, ADT of ueue, Types of Queue-Circular Queue, Priority Queue, If a stack is not empty, then pop the element from its top (similar to delete() from a list) PoP() Returns the top element. display_top() + 6, 2.3 _ Array Representation ‘A one-dimensional array can be used to hold elements of a stack, Another variable “top” is used to keep track of the index of the top most element. 3 1 top stack grows from flo rght Indox 2 4 on 9 Array Formally, a stack may be defined as follows. typedef struct stack { int data[MAX]; int top; }stack; /*Max is a constant, maximum number of elements that can be stored */ Initially, top is set to—1 A stack with top as —1 is an empty stack. When the value of top becomes MAX — 1 after a series Of insertions, itis full. After “push” operation top = top + 1 (Stack Growing) After “pop” operation top = top ~ 1 (Stack Shrinking) 7 $F Data Structure (MU-Comp.) 22 Stack and Queues, 2.3.1 Functions for Primitive Operations | | void push(stack *S, int x) ona Stack { 7 S-> top =S-> top + 1; ‘oid initialize(stack *S) a> uind> w= t INote: Main program should ensure that the stack is not) full before making a call to push{ ) function. It may Initially, stack is empty. cause an overtlow, otherwise. Pointer to Stack type variable Stack type variable int pop(stack *S) —_, Dar] { s}+— 2 Plies int xs & : =S> > wok S-+Deta{!] _ —+ Melement of he aay 5 a7 Satals -> wr] eS SS panne $ -> top = $->top—1; S-+ Data [S-+top] —> top element of the stack return(x); Accessing elements of a stack using a pointer p int display * EGS) ie dlisplay_top(stack *S) { int fe oy) item) . => data [S-> top)); P(e F Se is emity *Y return(S -> data [ ; ts ; return(0); /* stack empty condition is false*/ ; return Tt dfs etaak ss eriely + ‘Above function checks whether a stack i empty | [Nol®: Main program shoud ensure that the stack isn [containing 0 elements). Function returns a value (true if omvoly elore making a callie pop | suncton: ey the stack is empty. Function returns a value 0 (False) if the -Sause an under fow, otherwise, ____| stack isnot empty (there are some elements) The function push increase the value of the top by 1 o res the element at the top location in “data” Sergi) : senses he emetotesrton et { : The function pop{ ) returns the top elements from the if( S->top == MAX -1) stack. It also, reduces the value of top by 1 (one element is retum(1); deleted from the stack). return(0); ; ; 2.3.2. Program Showing Stack Operations Scare aii aenae one caTaeD Convert a decimal number to binary using a stack. Example: a aca ample Input number = 23 (Decimal) hep 21%2=1 1 ‘Above function checks whether a stack is fll (no more elements can be added.) Function returns a value 2 (true) if ° the stack is ful, Function returns a value 0 (false) if the meee? stack is not full (more elements could be added). E oa SK A Oy 4 At Qing ty Structuro (MU-Comp. 5 Fnusveni 1 ‘inti Enter decimal number), SS ah 0 sscant("96dl", &x)i . Lt. while((xt = 0) { i if¢tfull(&a)) | 2%2"0 a 0 { 1 push (Bim, x962)5, x= /2; 1 } ° ol IMZ"1 1 ane 0 { 1 printf("n stack overflow"); QD = (10101) exit(0) A decimal number can be converted to binary from } through repeated division of the number by 2. Remainder } at each step is saved in a stack. Finally, the bits stored in printi(\n stack can be printed one by one through POP( ) operation. i ‘ while(lempry(&s)) Program 2.3.1: Program for conversion of decimal { number to binary form. oR Write a °C’ program to convert decimal x = pop(&s); | to binary using any appropriate data printf("%d", x); | ‘structure you have studied. } | 7 } ‘#indude void init(stack *s) #inelude { ‘#define MAX 20 | 8->top = -1; | typedef struct stack ) | { , int detefMAXY, int emply(stack *s) | int op ‘ | ya if(e->top == -1) | void init(stack *}; return(1); | int empty(stack *) return (0); int full(stack *); } | int pop(stack *); int full(stack #3) void push(stack *, int); { | void main( ) if(e->top == MAX-1) { retum(); stack 5; return(0); int x; } Se | Vold push(stack *s, int x)

You might also like