Programming in c

132
Globsyn Programming in C Part - II globsyn technologies XI - 11 & 12, Block - EP, Sector - V, Salt Lake Electronics Complex, Calcutta - 700091, India TechnoCampus UCP

description

Programming in C Part - II • Single Linked List • Doubly Linked List • Stack, Queue, and Binary Trees • Enhanced Searching — Indexing & Hashing Using Data Structure • C Library

Transcript of Programming in c

  • Globsyn

    Programming in C

    Part - II

    globsyn technologies XI - 11 & 12, Block - EP, Sector - V, Salt Lake Electronics Complex,

    Calcutta - 700091, India

    TechnoCampus UCP

  • All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein.

    YM/SR/CPRG2/1.0

  • Programming in C - Part II

  • Programming in C Part II

    YM/SR/CPRG2/1.0 1

    Programming in C Part II

    Single Linked List ------------------------------------------------------------------------------------ 3 Data Structure - The need------------------------------------------------------------- 4 Single Linked List -------------------------------------------------------------------- 5 Single Linked List in C --------------------------------------------------------------- 7 Creation of a List---------------------------------------------------------------------- 8 Insertion of nodes in an existing list -------------------------------------------------12 Sorted Linked List -------------------------------------------------------------------16 Traversal in the list-------------------------------------------------------------------20 Search for a specific node------------------------------------------------------------24 Deletion of a node -------------------------------------------------------------------28 Quiz ----------------------------------------------------------------------------------32 Summary-----------------------------------------------------------------------------33

    Doubly Linked List----------------------------------------------------------------------------------34 Concept of doubly linked lists -------------------------------------------------------35 Structures in C to represent doubly linked list ---------------------------------------37 Inserting a node in doubly linked list ------------------------------------------------38 Traversing in doubly linked list------------------------------------------------------45 Quiz ----------------------------------------------------------------------------------49 Summary-----------------------------------------------------------------------------50

    Stack, Queue and Binary Tree-------------------------------------------------------------------51 Stacks in C ---------------------------------------------------------------------------53 The push() and the pop() functions --------------------------------------------------54 Appreciating queue in C -------------------------------------------------------------57 Structures in C to represent queue ---------------------------------------------------58 Insert and delete in queue ------------------------------------------------------------59 The concept of Binary trees----------------------------------------------------------62

    Programming in C -- Part II

    Single Linked List

    Doubly Linked List

    Stack, Queue, and Binary Trees

    Enhanced Searching Indexing & Hashing

    Using Data Structure

    C Library

  • Programming in C Part II

    YM/SR/CPRG2/1.0 2

    Binary trees with structures in C-----------------------------------------------------66 Insert node in binary tree ------------------------------------------------------------67 Traversing a binary tree --------------------------------------------------------------74 Deletion of a Node from Binary tree ------------------------------------------------79 Quiz ----------------------------------------------------------------------------------83 Summary-----------------------------------------------------------------------------84

    Enhanced searching Indexing & Hashing using Data structure -------------------85 Search Methods ----------------------------------------------------------------------86 Indexed Searching -------------------------------------------------------------------89 Structure in C to represent an Index -------------------------------------------------91 Create an Index for a Data file -------------------------------------------------------93 Hashing ---------------------------------------------------------------------------- 102 Hashing Functions ----------------------------------------------------------------- 104 Hashing Techniques --------------------------------------------------------------- 105 Hash Indexes----------------------------------------------------------------------- 106 Hash Tables ------------------------------------------------------------------------ 108 Collisions -------------------------------------------------------------------------- 109 A complete Example --------------------------------------------------------------- 112 Quiz -------------------------------------------------------------------------------- 119 Summary--------------------------------------------------------------------------- 120

    C Library --------------------------------------------------------------------------------------------121 Need of software library ----------------------------------------------------------- 122 Creation and maintenance of software library------------------------------------- 123 Using the Library ------------------------------------------------------------------ 127 Quiz -------------------------------------------------------------------------------- 128 Summary--------------------------------------------------------------------------- 129

  • Programming in C Part II

    YM/SR/CPRG2/1.0 3

    Single Linked List

    At the end of the chapter, you will be able to:

    Appreciate the need of Data Structure

    Appreciate the concept of Linked List

    Appreciate Linked List in C

    Create Linked List

    Insert nodes in an existing single Linked List

    Create sorted Linked List

    Traverse the list

    Search a Node in a single Linked List

    Delete a Node in a single Linked List

    Single Linked List

    Appreciate the need of Data Structure Appreciate the concept of Linked List

    Appreciate Linked List in C Create Linked List Insert of nodes in an existing single Linked List Create Sorted Linked List Traverse the list Search a Node in the Single Linked List Delete of a Node in single Linked List

  • Programming in C Part II

    YM/SR/CPRG2/1.0 4

    Data Structure - The need

    If the oft-repeated question, why do we use computers, is asked, then don't get irritated. It is obvious that you know the answer but still lets recapitulate it once more. One of the most important jobs performed by computers is, storing and manipulating information. A data structure is a method of data representation in a logical manner. The representation of data is made in the memory using simple and complex data types. In C, we will be studying data structures from two perspectives: Identify and understand some high-level data type as tool to represent and

    organize data.

    Implementation of such data type using existing data types.

    Already we have seen some existing data structures in C like arrays and structures. You must be familiar with using these structures and reaping the benefit out of it. For the rest of the chapter, we will concentrate on developing more complex data types and how they can be used under different problem scenarios.

    Data Structure - The need

    A data structure is a method of data presentationin a logical manner.

    Representation of data is made in the memoryusing simple and complex data types.

    Data structures are used for managing andmanipulation of huge data efficiently.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 5

    Single Linked List

    Lets consider the invoicing system for ABCs retail shop. When the bill is prepared, can anybody guess about the number of items that the customer is going to purchase? He may buy 1 item or 10 items depending upon his pocket and his mood, and his need ofcourse! So while writing a program, to represent this bill in the memory, the help of data structure is required. Since already you know about arrays, your first choice will be to represent the bill with the help of an array. But, just words of caution over here, that working with the array in this situation might not be a very pleasant experience. But WHY? Let's try to justify. Since already you have seen that the number of items in the bill is variable, how can we determine the size of the array? If you are taking a large sized array, to play safe, but the number of items happens to be small, you would be simply wasting space. On the other hand, if you are declaring the array size too small, then you will not be able to store all the items, if the number of items is large. In addition, if you have to insert or delete data in the middle of an array you have to go through rigmarole. This will involve restructuring of the array. In this type of situation, Linked List comes to be quite handy. Linked lists are a group of self-referential structures. A linked list is a chain of structures, which has a data part and pointers. The pointer stores the address of the next structure in the list.

    Single Linked List

    Link lists are a group of self-referential structure. It is a chain of structures, which has a data part

    and pointers, which store the address of the nextstructure in the list.

    200

    I001 215 I002 232 I003 Null

    200 215 232

    DataAddress

    DataAddress

    DataAddress

  • Programming in C Part II

    YM/SR/CPRG2/1.0 6

    The items that you can see in the figure are called nodes. It contains two parts, the data part and an address part. Let's understand the concept with the help of an example of billing for ABC shop.

    start

    As you can see in the above figure that there are three nodes in the linked list. Each node has two parts. The first part consists of the data. In our example it is only containing the Item Code. It can also be a variable of a derived data type like structure. The other part is a pointer that contains the address of the next node. You can see that the third node is the last one in the chain. Its pointer contains Null since there is no next node to point. As you know, every thing has a starting. In the same manner, we have keep track of the very first node of the list. This helps in accessing the first node, and then we can navigate to any other node. If you look at the figure, you will find that both in the address field and on top of the nodes, certain numbers are written. These numbers notify the memory addresses of the nodes. We have assigned certain arbitrary numbers to represent the addresses, in reality these memory addresses can be altogether different.

    200

    I001 215 I002 232 I003 Null

    200 215 232

    Data Address Data Address Data Address

  • Programming in C Part II

    YM/SR/CPRG2/1.0 7

    Single Linked List in C

    After discussing the concepts of Linked List, lets try to understand its implementation in C. In our previous discussions, we have seen that to implement a list, the first step is to create a node. Nodes contain a data part and an address part. Nodes can best be represented in C with the help of structures. A node can be represented in the following way:

    struct bill{ char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; };

    You can see from the above code snippet that the first four elements of the structure bill represent the data part, and the last element is a pointer of the same structure, as that of bill. This will point to the next node, which will be of the same type as bill. Once we have declared the node, let's try to create a linked list. We will concentrate on: Creation of a list

    Insertion of nodes in an existing list

    Traversal of the list

    Deletion of a node from the list

    Searching for a specific node in the list

    Single Linked Lists in C

    In C a single linked list is made up of Nodes. Node contains a data part and an address part. Node can be best represented in c with the help

    of a structure. The node can be represented like this:

    struct bill{

    char itemno[5];char itemdesc[30];float rate;int qty;struct bill *next;

    };

  • Programming in C Part II

    YM/SR/CPRG2/1.0 8

    Creation of a List When we say creation of a list, we mean adding a node to an empty list. That is the list is created for the first time. After creation of the list, we can go on adding other nodes to the existing list.

    Generally, the functions, for adding a node to an empty list, and for adding a new node to an existing list, are clubbed together into a single function for programming convenience. A check is made to ascertain whether start is NULL or not. If start is Null, the list is empty, otherwise the list exists.

    The steps to create a list are: Create a structure, as we have seen earlier.

    Declare a pointer, say start, of the structure type declared earlier, and initialize it with NULL.

    Create a new node.

    Store the address of the newly created node in the start.

    struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; }; char c; struct bill *start;

    Creation of a List

    By creation of a list we mean adding a node to anempty list.

    The steps to create a list are: Create a structure as we have seen earlier. Declare a pointer, say start of the structure type and

    initialize it with NULL. Create a new node Store the address of the newly created node in the

    start.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 9

    main() { . . . add(); . .. } add() { struct bill *createnode(),*new; new=createnode(); // Creating a new node which we will be

    // Discussed a bit later. if(start==NULL) {

    start=new; //The address of the newly created node is //stored in the start

    return; } .. }

    From the above code, it is clear that a self-pointing structure called bill has been created. After that, we are declaring a pointer called start of type bill structure. Then from the main() method we are calling a method called add(). In the add() method we have declared a pointer called new. This is used to store the address of the newly created node, returned by the function createnode(). The function createnode() dynamically creates a node. Soon we will be discussing how it dynamically creates a node. Then start is checked to make sure whether it is NULL or not. If it is NULL, it means that the list is empty. So the address of the new node is assigned to the start. In this way we have created the list with a single node. Now let's look into the function createnode(), in detail.

    struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :");

  • Programming in C Part II

    YM/SR/CPRG2/1.0 10

    printf("\n\t Item No:\t");

    scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); };

    Let's now explore the function. The main advantage provided by linked list, as have often been mentioned, is the flexibility of adding elements without bothering about a predefined number (of elements). It requires us to reserve memory for the nodes during the runtime of the program. This technique of allocating memory during execution of the program (unlike allocating memory during the compilation time) is called dynamic memory allocation. Using this technique, we will be allocating memory when a node is created, and releasing it when a node is deleted. Dynamic memory allocation in C, is done through a standard library function called malloc().

    char *malloc(unsigned size_of_memory_to_be_allocated) Another library function, called calloc(), is also available. It is being consciously overlooked, since we will not use it in our programs. The function malloc(), reserves a chunk of memory as specified by the parameter passed to it. It returns a character type pointer to the first byte of the chunk reserved. We can use this pointer to access the reserved memory location. If this function fails to reserve the memory due to some reason, it returns a NULL value.

    To use the function malloc() you may have to include the header file called malloc.h. This header file contains the declaration of this function.

    In this program snippet, from the function createnode(), we are using malloc() to reserve memory:

    new1=(struct bill*)malloc(sizeof(struct bill));

  • Programming in C Part II

    YM/SR/CPRG2/1.0 11

    Here malloc() is being used to allocate memory for a node. The size of the structure is passed (with the help of sizeof() operator) as an argument to the function specifying the amount of memory to be allocated. Since, malloc() returns a character type pointer, therefore the return value is type cast to a pointer to structure of type bill. The rest of the code is very simple. Accepting the details from the user and assigning them to different member variable of the structure and ultimately returning the address of the newly created Node.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 12

    Insertion of nodes in an existing list

    We have already created a node. Now, we will add a node to an existing list. In this case, we will add a node at the beginning of the list. #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; }; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the list"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); }

    Insertion of nodes in an existing list

    To add a node at the start of a list: link the new node to the first node of the existing node. pointer of the new node should point to the address of

    the first node of the existing node.

    200

    I001 215 I002 232 I003 Null

    200 215 232

    Data Address

    I004 NULL

    178

    178

    New

    Data Address Data Address Data Address

  • Programming in C Part II

    YM/SR/CPRG2/1.0 13

    if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new; new=createnode(); if(start==NULL) { start=new; return; } new->next=start; start=new; return; } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); }

    The above code is used for adding a node to an existing list.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 14

    The following figure shows the existing list:

    To add a new node to this existing list at the beginning of the list it has to be arranged like the figure below. From the figure above, it is clear that we have to do the following tasks to add the new node to the existing list: 1. We have to link the new node to the first node of the existing node. That is, the pointer of the new node should point to the address of the first node of the existing list. The address of the first node is contained in the start pointer.

    This is done by issuing the statement:

    new->next=start; 2. Since, the new node has been inserted at the beginning of the list, therefore start should point to the new node. Instead of 200 start should now contain the address 178.

    200 start

    I001 215 I002 232 I003 Null

    200 215 232

    Data Address Data Address Data Address

    200 start

    I001 215 I002 232 I003 Null

    200 215 232

    Data Address

    I004 Null

    178 178 New

    Data Address Data Address Data Address

  • Programming in C Part II

    YM/SR/CPRG2/1.0 15

    The following statement does the job of reassigning start:

    start=new; This type of list, where a node is inserted at the beginning of the list, and is not arranged in a specific pattern, with respect to their data, is termed as unsorted list. But for most of the purpose like getting a piece of information as report, we require a sorted linked list.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 16

    Sorted Linked List Sorted lists are those, where the nodes are inserted into the list on the basis of their data part. The nodes having the smaller data part is added before the nodes with larger data part. The figure above shows a sorted linked list. The list is sorted in ascending order on the basis of the data part. Now, say there is a new node with Item Code I003. The question is where should this node be inserted in the list.

    200

    I001 215 I002 232 I004 Null

    200 215 232

    Data Address Data Address Data Address

    I003 X

    110

    New

    Sorted Linked List

    Sorted list are those type of list where the nodesare inserted into the list on the basis of the datapart.

    The nodes having the smaller data part is addedbefore the nodes with larger data part.

    200

    I001 215 I002 232 I004 Null

    200 215 232

    Data Address Data Address Data Address

    215

    prev

    232

    ptr

    I003 X110

    new

    110

  • Programming in C Part II

    YM/SR/CPRG2/1.0 17

    Since the data part of the new node, i.e. I003, is lest than the data part of the last node, i.e. I004, so it will be added before the 3rd (or the last) node, and after the 2nd node of the existing list. How can we achieve this? A pointer, say ptr, has to be positioned at the node with data I004, because

    a link has to be established with the new node. Generally speaking, a pointer has to be positioned on the node before which the new node will be inserted.

    Another pointer, say prev, should be positioned at the node after which the new node will be added. In this case, it will be on 2nd node (that is containing the data I002). This is necessary, since a link has to be established with the new node to be inserted.

    How can we position the pointers on the specific positions?

    To position the pointers on the specific nodes, advance the pointer ptr from the beginning of the list till it reaches the first node with data greater than the data contained in the new node. The pointer prev, which is made to follow the ptr, thereby points to the node just before the node that ptr is pointing to. The figure above depicts how a node can be inserted in the middle of the list. This is how you will create the sorted linked list. Lets now see the code to achieve this: #include #include struct bill {

    200

    I001 215 I002 232 I004 Null

    200 215 232

    Data Address Data Address Data Address

    215 prev

    232 ptr

    I003 X 110 new

    110

  • Programming in C Part II

    YM/SR/CPRG2/1.0 18

    char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; }; char c; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the list"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new,*ptr,*prev; new=createnode(); if(start==NULL) { start=new; return; } for(ptr=start;(ptr)&&strcmp(new->itemno,ptr->itemno)>0; prev=ptr,ptr=ptr->next); if(ptr!=start) { prev->next=new; new->next=ptr; } else { new->next=start; start=new; }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 19

    return; } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); }

    In the above program, the additional new codes are in bold text. Let's now take a look at them: for(ptr=start;(ptr)&&strcmp(new->itemno,ptr->itemno)>0; prev=ptr,ptr=ptr->next); The above code snippet helps us in positioning the pointers prev and ptr to the appropriate node. After positioning the prev and ptr to the respective nodes, the new node has to be linked. The following block of code does this: if(ptr!=start) { prev->next=new; new->next=ptr; } else { new->next=start; start=new; }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 20

    Traversal in the list To show the data stored in the linked list or to manipulate it, we have to traverse it. For example, if we want to extract all the data stored in the linked list, we have to move from the beginning to the end of the list. Look at the code given below, which handles the traversal of the list. The bold portion of the code is actually doing the job. #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; }; char c; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear");

    Traversal in the list

    steps followed to traverse a list. Declare a pointer to struct bill say in the example it is ptr. Assign the address stored in the start to ptr assuming that

    the list already exist. Print the data contained by the node currently being

    pointed by ptr. Reinitialize the pointer ptr with the address of the next

    node. Repeat the previous two steps until ptr encounters NULL..

  • Programming in C Part II

    YM/SR/CPRG2/1.0 21

    printf("\n\n I. Insert into the list"); printf("\n D. Display the List"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='D')||(choice=='d')) { display(); } if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new,*ptr,*prev; new=createnode(); if(start==NULL) { start=new; return; } for(ptr=start;(ptr)&&strcmp(new->itemno,ptr->itemno)>0;prev=ptr,ptr=ptr->next); if(ptr!=start) { prev->next=new; new->next=ptr; } else { new->next=start; start=new; } return; } display() { struct bill *ptr;

  • Programming in C Part II

    YM/SR/CPRG2/1.0 22

    printf("\n\nItem code\tDescription\tRate\t Quantity sold\n"); for(ptr=start;(ptr);ptr=ptr->next) { printf("%s\t ",ptr->itemno); printf("%s\t ",ptr->itemdesc); printf("%f\t ",ptr->rate); printf("%d\t\n ",ptr->qty); } c=getchar(); } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); }

    Looking at the function display(), in the above code, we find that the following steps are required to traverse a list: Declare a pointer to struct bill, which is ptr in our example.

    Assign the address stored in start to ptr, assuming the list already exist.

    Print the data contained by the node currently being pointed to by ptr

    Re-initialize the pointer ptr with the address of the next node.

    Repeat the previous two steps until ptr encounters NULL.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 23

    The output of the program is given below:

  • Programming in C Part II

    YM/SR/CPRG2/1.0 24

    Search for a specific node Once we know how to traverse a linked list, searching for a particular node and changing the data of that node will not be a great problem. The logic will be the same as that of traversing the list, only we have to give another extra condition to find whether the data searched is equivalent to the data of the node currently pointed to or not. Once we accessed the desired node, changing the data of that node is very simple. Consider the following code, which achieves this: #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; }; char c; char icode_del[5]; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear");

    Search for a specific node

    logic will be same as that of traversing the list, only wehave to give another extra condition to find whether thedata searched is equivalent to the data of the nodecurrently pointed or not.

    for(ptr=start;(ptr);prev=ptr,ptr=ptr->next){if(strcmp(icode_del,ptr->itemno)==0){

    //code to do certain task}

  • Programming in C Part II

    YM/SR/CPRG2/1.0 25

    printf("\n\n I. Insert into the list"); printf("\n D. Display the List"); printf("\n S. search a node"); printf("\n Q. Quit"); printf("\n\n\t Enter your choice :\t"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='D')||(choice=='d')) { display(); } if((choice=='Q')||(choice=='q')) { exit(); } if((choice=='S')||(choice=='s')) { search(); } } } add() { struct bill *createnode(),*new,*ptr,*prev; new=createnode(); if(start==NULL) { start=new; return; } for(ptr=start;(ptr)&&strcmp(new->itemno,ptr->itemno)>0;prev=ptr,ptr=ptr->next); if(ptr!=start) { prev->next=new; new->next=ptr; } else { new->next=start; start=new; } return; }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 26

    display() { struct bill *ptr; printf("\n\nItem code\tDescription\tRate\t Quantity sold\n"); for(ptr=start;(ptr);ptr=ptr->next) { printf("%s\t ",ptr->itemno); printf("%s\t ",ptr->itemdesc); printf("%f\t ",ptr->rate); printf("%d\t\n ",ptr->qty); } c=getchar(); } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); } search() { struct bill *ptr,*prev; printf("\nEnter The Item code to Search :\t"); scanf("%s",icode_del); fflush(stdin); for(ptr=start;(ptr);prev=ptr,ptr=ptr->next) { if(strcmp(icode_del,ptr->itemno)==0) { printf("Description :\t%s\n ",ptr->itemdesc); printf("Rate :\t%f\n ",ptr->rate); printf("Quantity :\t%d\n ",ptr->qty); c=getchar(); return; } }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 27

    printf("\nNo such item found"); c=getchar(); return; }

    To your existing code you just have to add the codes in bold. If you supply a particular Item Code it will search and show you the other details pertaining to that Item. If you execute the program, the following will be its output:

  • Programming in C Part II

    YM/SR/CPRG2/1.0 28

    Deletion of a node To delete an existing node from a linked list we have to follow the following steps. We have to traverse the list and point to the node that has to be deleted. This

    can be done in a manner similar to what we did while traversing the list.

    If and when we find the node to be deleted, we have to logically delete it first. In other words, the node before the one marked for deletion has to be connected to the node just it (the one marked for deletion). So we have to keep another pointer say prev to point to the node just before the node to be deleted.

    From the above figure, you find that the node with the item code I002 has to be deleted. That requires pointer ptr to be positioned on the node (to be deleted),

    200 start

    I001 215 I002 232 I004 Null

    200 215 232

    Data Address Data Address Data Address

    200 prev

    215 ptr

    Deletion of a node

    To delete the node logically i.e. node previous tothe node marked for deletion has to be connectedto the node just after the node marked fordeletion.

    200

    I001 215 I002 232 I004 Null

    200 215 232

    Data Address Data Address Data Address

    200

    prev

    215

    ptr

  • Programming in C Part II

    YM/SR/CPRG2/1.0 29

    and another pointer, say prev, to be positioned on the previous node with data I001. Once the pointers are positioned appropriately, you have to just link the first node with the third node, so that logically the second node is deleted from the list. This linking can be achieved by writing the following code.

    prev->next=ptr->next;

    This code holds true for deleting any node from the beginning or the end of the list. A slight change is required in the code for deleting the first node from the list. The start then needs to point to second node.

    start=ptr->next;

    Even after you have logically deleted the desired node, the node still exists physically in the memory. To delete it physically, use the library function free(). Let's now look into the complete code for the deletion of node from a list #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *next; }; char c; char icode_del[5]; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the list"); printf("\n D. Display the List"); printf("\n X. Delete a node"); printf("\n Q. Quit"); printf("\n\n\t Enter your choice :\t"); choice=getchar();

  • Programming in C Part II

    YM/SR/CPRG2/1.0 30

    fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='D')||(choice=='d')) { display(); } if((choice=='Q')||(choice=='q')) { exit(); } if((choice=='X')||(choice=='x')) { remove1(); } } } add() { struct bill *createnode(),*new,*ptr,*prev; new=createnode(); if(start==NULL) { start=new; return; } for(ptr=start;(ptr)&&strcmp(new->itemno,ptr->itemno)>0;prev=ptr,ptr=ptr->next); if(ptr!=start) { prev->next=new; new->next=ptr; } else { new->next=start; start=new; } return; } display() { struct bill *ptr; printf("\n\nItem code\tDescription\tRate\t Quantity sold\n"); for(ptr=start;(ptr);ptr=ptr->next) {

  • Programming in C Part II

    YM/SR/CPRG2/1.0 31

    printf("%s\t ",ptr->itemno); printf("%s\t ",ptr->itemdesc); printf("%f\t ",ptr->rate); printf("%d\t\n ",ptr->qty); } c=getchar(); } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); } remove1() { struct bill *ptr,*prev; printf("\nEnter The Item code to delete :\t"); scanf("%s",icode_del); fflush(stdin); for(ptr=start;(ptr);prev=ptr,ptr=ptr->next) { if(strcmp(icode_del,ptr->itemno)==0) { if(ptr==start) { start=ptr->next; return; } else { prev->next=ptr->next; return; } free(ptr); } } printf("\nNosuch item found"); return; }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 32

    Quiz

    Quiz

    What is the difference between sorted and unsortedsingle link list?

    Write a function to insert a node at the beginning of anunsorted single linked list.

    Write a function to insert a node in a sorted singlelinked list.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 33

    Summary

    At the end of this chapter, you will now be able to:

    Appreciate the need of Data Structure

    Appreciate the concept of Linked List

    Appreciate Linked List in C

    Create Linked List

    Insert nodes in an existing single Linked List

    Create sorted Linked List

    Traverse the list

    Search a Node in a single Linked List

    Delete a Node in a single Linked List

    Summary

    After the completion of this module now youwill be able to:

    Appreciate the need of Data Structure Appreciate the concept of Linked List Appreciate Linked List in C Create Linked List Insert of nodes in an existing single Linked

    List Create Sorted Linked List Traverse the list Search a Node in the Single Linked List Delete of a Node in single Linked List

  • Programming in C Part II

    YM/SR/CPRG2/1.0 34

    Doubly Linked List

    At the end of this module, you will be able to:

    Learn the concept of doubly linked lists

    Use structures in C to represent doubly linked list

    Insert in doubly linked list

    Traverse in doubly linked list

    Doubly Linked List

    Learn the concept of doubly linked lists Use structures in C to represent doubly linked

    list Insert in doubly linked list Traversing in doubly linked list

  • Programming in C Part II

    YM/SR/CPRG2/1.0 35

    Concept of doubly linked lists

    After discussing the Single linked list, you must now be conversant with the concepts of linked list. In the previous chapter you have learnt how to organize data in the memory, so as to retrieve it efficiently as and when required. But you must have noticed one limitation of single liked list in case of data retrieval. While retrieving data from the single linked list, we can only move forward. There is no way we can move backward. This is because every node only contains the address of the next node, and not the previous node. For certain kind of applications this can be a big constraint e.g. database applications. So, you must be wondering about the solution of this shortcoming. The answer of C to this problem is, doubly linked list.

    NULL I001 176 150 I002 197 176 I003 NULL

    150 197

    Prev data Next Prev data Next Prev data Next

    Start Last

    150 176 197

    Concept of doubly linked lists

    Doubly linked list is very similar to single linked list butdiffers in having two pointers instead of a single pointer.

    It is also a self referential structure containing the addressof both the next and the previous node.

    NULL I001 176 150 I002 197 176 I003 NULL

    150 197

    Prev data Next Prev data Next Prev data Next

    StartLast

    150 176 197

  • Programming in C Part II

    YM/SR/CPRG2/1.0 36

    From the figure above, you find that doubly linked list differs from the single linked list in having two pointers, one pointing to the next node and the other pointing to the previous one. Only the first and the last nodes are the exception. The first node only points to the next node, and the last node points only to the previous node. Like single linked list, start contains the address of the first node. An additional pointer, i.e. last, contains the address of the last node.

    Now, the question is how to represent doubly linked list in C?

    We will give answer to this question in the next section.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 37

    Structures in C to represent doubly linked list

    We have already discussed the use of structure to represent single linked list. You will find not much difference in the representation of doubly linked list. The only difference that you will find is that it contains an additional pointer to the structure itself. Given below is a typical representation of a structure for implementation of doubly linked list:

    struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *prev; //pointer to point to the previous node struct bill *next; //pointer to point to the next node };

    If you consider the above code you will find that there is an extra pointer, called prev, which will point to the previous node. After knowing how to represent a node of a doubly linked list, let's find out how to create and manipulate such lists.

    Structures in C to represent doublylinked list

    Nodes in doubly linked list are represented with the helpof structure.

    struct bill{

    char itemno[5];char itemdesc[30];float rate;int qty;struct bill *prev; //pointer to point to

    // the previous nodestruct bill *next; //pointer to point to // the next node

    };

  • Programming in C Part II

    YM/SR/CPRG2/1.0 38

    Inserting a node in doubly linked list

    Inserting a node in a doubly linked list is not much different from inserting a node in a single linked list. The only extra job that you have to do is maintain two pointers, one pointing to the next node and the other pointing to the previous one of the list. During insertion of a node in a list, there can be three situations: Insertion at the beginning of a list

    Insertion in the middle of a list

    Insertion at the end of a list

    Insertion at the beginning of a list NEW You can find from the figure above, that node pointed to by the pointer new will be inserted before the node pointed by the pointer start.

    NULL I001 176 150 I002 197 176 I003 NULL

    150 197

    Prev data Next Prev data Next Prev data Next

    Start

    Last

    150 176 197

    NULL I004 150

    Prev data Next

    120

    120

    Inserting a node in doubly linked list

    Insertion in doubly linked list can be of three types Insertion at the beginning of a list Insertion in the middle of a list and at the end of a list

    NULL I001 176 150 I002 197 176 I003 NULL

    150

    197

    Prev data Next Prev data Next Prev data Next

    Start

    Last

    150 176 197

    NULL I004 150

    Prev data Next

    120

    120

    NULL I001 176 150 I002 197 176 I005 NULL

    150197

    Prev data Next Prev data Next Prev data Next

    StartLast

    150 176 197

    NULL I004 NULLPrev data Next

    120

    120New

    Prev1 Ptr

  • Programming in C Part II

    YM/SR/CPRG2/1.0 39

    The code below shows the addition of a node at the beginning of a list: #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *prev; struct bill *next; }; char c; struct bill *start; main() { char choice; choice='x'; start=NULL; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the list"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new; new=createnode(); if(start==NULL) { start=new; return; } new->next=start; start->prev=new; start=new; return;

  • Programming in C Part II

    YM/SR/CPRG2/1.0 40

    } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); }

    The code, which is in bold, is for handling the addition of a node at the beginning of a list. You have to first of all check, whether the list exists or not. This can be done with the help of the start pointer. If the start pointer is NULL then the list is empty. So you just have to assign the address of the first node to the start pointer.

    if(start==NULL) { start=new;

    return; }

    If the list already exists, the next pointer of the new node should store the address of the node pointed by the start pointer.

    new->next=start; The prev pointer of the node pointed by start pointer should contain the address of the new node.

    start->prev=new; The start pointer should contain the address of the new node.

    start=new;

  • Programming in C Part II

    YM/SR/CPRG2/1.0 41

    Insertion of a node in the middle and at the end of a list

    Insertion in the middle of the list is very similar to that of a single linked list. Only thing that you have to do is to maintain two pointers next and prev while linking the nodes. The code is given below: #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *prev; struct bill *next; }; char c; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the list"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin);

    NULL I001 176 150 I002 197 176 I005 NULL

    150 197

    Prev data Next Prev data Next Prev data Next

    Start

    Last

    150 176 197

    NULL I004 NULL

    Prev data Next

    120

    120

    New

    Prev1 Ptr

  • Programming in C Part II

    YM/SR/CPRG2/1.0 42

    if((choice=='I')||(choice=='i')) { add(); } if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new,*prev1,*ptr; new=createnode(); if(start==NULL) //Adding a node in an empty list { start=new; return; } for(ptr=start;(ptr)&&strcmp(new->itemno,ptr-> itemno)>0;prev1=ptr,ptr=ptr->next); if(ptr!=start&&ptr!=NULL) //Adding the node in the middle { new->next=ptr; new->prev=prev1; prev1->next=new; ptr->prev=new; } else { if(ptr==NULL) //Adding the node at the end of the node { new->next=ptr; new->prev=prev1; prev1->next=new; } else { new->next=start;// If the new node is the first node start=new; new->prev=NULL; } } }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 43

    struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); }

    As you can see from the add() function, which is in bold, we are writing three different code snippet for adding, in the existing list. If the node inserted is in between two nodes, you have to position the two pointers appropriately. That is, ptr will point to the node before which the new node is inserted and prev1 points to the node after which the new node will be inserted. This positioning of the two pointers is done in the same way as it happened in the single linked list. After that you have to write the following code snippet to link the nodes:

    new->next=ptr; new->prev=prev1; prev1->next=new; ptr->prev=new;

    If the new node added happens to be the last node then you have to place the ptr and prev1 accordingly.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 44

    Following this, you have to link the nodes using the following code snippet:

    new->next=ptr; new->prev=prev1;

    prev1->next=new;

    If the new node is supposed to be added in an existing list and that node happens to be the first node, then the following code snippet is used to link the nodes:

    new->next=start; start=new;

    new->prev=NULL;

    NULL

    I001 176 150 I002 197 176 I005 NULL

    150 197

    Prev data Next Prev data Next Prev data Next

    Start

    Last

    150 176 197

    NULL

    I004 NULL

    Prev data Next

    120

    120

    New

    120 NULL prev1

    Ptr

  • Programming in C Part II

    YM/SR/CPRG2/1.0 45

    Traversing in doubly linked list

    Traversing the doubly linked list is very similar to the traversing in the single linked list. The only difference, and its an advantage, is that of the movement in both the direction. The following code explains how this can be achieved: #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *prev; struct bill *next; }; char c; struct bill *start; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the list"); printf("\n D. Display the List"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i'))

    Traversing in doubly linked list

    display(){

    struct bill *ptr,*last,*x;for(ptr=start;(ptr);x=ptr,ptr=ptr->next);last=x;printf("press Next record, previous record, toExit\t");ptr=start;

    while((c!='E')&&(c!='e')){c=getchar();

    if((c=='n')||c=='N'){ptr=ptr->next;

    if(ptr==NULL){ptr=last;}printf("Item Code:\t %s\n ",ptr->itemno);}

    if((c=='p')||c=='P'){ptr=ptr->prev;

    if(ptr==NULL){ptr=start;}printf("Item Code: \t%s\n ",ptr->itemno);

    }}}

  • Programming in C Part II

    YM/SR/CPRG2/1.0 46

    { add(); } if((choice=='D')||(choice=='d')) { display(); } if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new,*prev1,*ptr; new=createnode(); if(start==NULL) { start=new; return; } for(ptr=start;(ptr)&&strcmp(new->itemno,ptr->itemno)>0;prev1=ptr,ptr=ptr->next); if(ptr!=start&&ptr!=NULL) { new->next=ptr; new->prev=prev1; prev1->next=new; ptr->prev=new; } else { if(ptr==NULL) { new->next=ptr; new->prev=prev1; prev1->next=new; } else { new->next=start; start=new; new->prev=NULL; } } } display()

  • Programming in C Part II

    YM/SR/CPRG2/1.0 47

    { struct bill *ptr,*last,*x; for(ptr=start;(ptr);x=ptr,ptr=ptr->next); last=x; printf("To First record press,Next record, previous record,Last record . to Exit\t"); ptr=start; while((c!='E')&&(c!='e')) { c=getchar(); if((c=='f')||c=='F') { ptr=start; printf("Item Code: \t%s\n ",ptr->itemno); printf("Description\t %s\n ",ptr->itemdesc); printf("Rate%f\t\n ",ptr->rate); printf("Quantity\t%d\n ",ptr->qty); } if((c=='n')||c=='N') { ptr=ptr->next; if(ptr==NULL) { ptr=last; } printf("Item Code:\t %s\n ",ptr->itemno); printf("Description\t %s\n ",ptr->itemdesc); printf("Rate%f\t\n ",ptr->rate); printf("Quantity\t%d\n ",ptr->qty); } if((c=='p')||c=='P') { ptr=ptr->prev; if(ptr==NULL) { ptr=start; } printf("Item Code: \t%s\n ",ptr->itemno); printf("Description \t%s\n ",ptr->itemdesc); printf("Rate%f\t\n ",ptr->rate); printf("Quantity\t%d\n ",ptr->qty); }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 48

    if((c=='l')||c=='L') { ptr=last; printf("Item Code: \t%s\n ",ptr->itemno); printf("Description \t%s\n ",ptr->itemdesc); printf("Rate%f\t\n ",ptr->rate); printf("Quantity\t%d\n ", ptr->qty); } } } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 49

    Quiz

    .

    Quiz

    How many pointers are declared in the structurewhich represents a node in doubly linked list?

    What is the difference in instructions betweeninserting at the middle of the linked list an at theend of the linked list.

    Write a code to search a particular node in adoubly linked list.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 50

    Summary

    After this chapter, you are now able to: Learn the concept of doubly linked lists

    Use structures in C to represent doubly linked list

    Insert in doubly linked list

    Traverse in doubly linked list

    Quiz

    How many pointers are declared in the structurewhich represents a node in doubly linked list?

    What is the difference in instructions betweeninserting at the middle of the linked list an at theend of the linked list.

    Write a code to search a particular node in adoubly linked list.

    Summary

    After the end of this chapter, now you areable to: Learn the concept of doubly linked lists Use structures in C to represent doubly linked

    list Insert in doubly linked list Traversing in doubly linked list

  • Programming in C Part II

    YM/SR/CPRG2/1.0 51

    Stack, Queue and Binary Tree

    At the end of the chapter, you will be able to:

    Appreciate Stacks in C

    Represent Stacks in C

    Use push() and the pop() functions

    Appreciate queue in C

    Use structures in C to represent queue

    Insert and delete in queue

    Appreciate the concept of Binary trees

    Implement Binary trees with structures in C

    Insert node in binary tree

    Traverse a binary tree

    Delete a node from a binary tree

    Stack, Queue and Binary Tree

    Appreciate Stacks in C Represent Stacks in C Use push() and the pop() functions Appreciate queue in C Use structures in C to represent queue Insert and delete in queue Appreciate the concept of Binary trees Implement Binary trees with structures in C Insert node in binary tree Search a node in a binary tree Traverse a binary tree

    Delete a node from a binary tree

  • Programming in C Part II

    YM/SR/CPRG2/1.0 52

    Appreciate Stacks in C

    You must have heard the term stack very frequently, i.e in the kitchen or music CD shop. It is one of the most useful and important concepts in computer science. We will try to discover its importance and implementation in C. Now the question is what is a stack. "A stack is an ordered collection of items into which new items may be inserted and older ones deleted, from only one end, called the top of the stack". To draw an analogy for stack in real life, just think about CD's piled one on top of the other.

    As you can see from the figure that if you want to add a new item, you have to put it on the top of the stack. Conversely, if you want to remove any item from the stack, you have to do it from the top again. That is the item added last will be removed first. Thus, stacks are also known as Last-In-First-Out (LIFO) lists.

    Appreciate Stacks in C

    "A stack is an ordered collection of items intowhich new items may be inserted and from whichitems may be deleted at one end, called top ofthe stack".

  • Programming in C Part II

    YM/SR/CPRG2/1.0 53

    Stacks in C

    By definition, a stack is an ordered collection of items. C already has a data type, i.e. array, which is a collection of ordered items. Therefore, we might think that array can be a choice to represent stack in C. But there are a lot of difference between stack and array. In array, the number of elements is fixed, and it is determined during the definition of the array. Whereas a stack has to be a dynamic object, whose size has to change on demand. Therefore we will represent stacks with the help of linked list. A stack item can be depicted in this form:

    struct stack { char itemno[5]; char itemdesc[30]; float rate; int qty; struct stack *next; }*new1,*top;

    You can see, from the above code, that a structure pointer, called top, has been declared. It points to the beginning of the stack.

    Stacks in C

    Stacks are represented with the help of linked list.

    struct stack{char itemno[5];char itemdesc[30];float rate;int qty;struct stack *next;

    }*new1,*top;

  • Programming in C Part II

    YM/SR/CPRG2/1.0 54

    The push() and the pop() functions

    One of the important tasks in stack implementation is to add to, and remove elements from it. The addition and deletion to a stack is conventionally known as push and pop respectively. The push() and the pop() functions are special cases of insertion and deletion from a linked list. You can only insert into, or delete from the top of a stack. These two functions are just special cases of insertion and deletion in a linked list. #include #include struct stack { char itemno[5]; char itemdesc[30]; float rate; int qty; struct stack *next; }*new1,*top; char c; main() { char choice; choice='x'; top=NULL; while((choice!='q')&&(choice!='E'))

    The push() and the pop() functions

    The addition and deletion to a stack is conventionally known as push() andpop() respectively.

    push(){new1=(struct stack*)malloc(sizeof(struct stack));

    printf("\n Enter :");printf("\n\t Item No:\t");scanf("%s",new1->itemno);fflush(stdin);printf("\n\tDescription:\t");scanf("%s",new1->itemdesc);fflush(stdin);printf("\n\t Rate:\t");scanf("%f",&new1->rate);fflush(stdin);printf("\n\t Quantity:\t");scanf("%d",&new1->qty);new1->next=top;top=new1;c=getchar();}

  • Programming in C Part II

    YM/SR/CPRG2/1.0 55

    { system("tput clear"); printf("\n\n I. Insert onto the Stack"); printf("\n D. Display the Stack"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { push(); } if((choice=='D')||(choice=='d')) { pop(); } } } push() { new1=(struct stack*)malloc(sizeof(struct stack)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); new1->next=top; top=new1; c=getchar(); } pop() { printf("Item Code: \t%s\n ",top->itemno); printf("Description\t %s\n ",top->itemdesc); printf("Rate%f\t\n ",top->rate); printf("Quantity\t%d\n ",top->qty); new1=top; top=top->next; free(new1); }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 56

    In code given above, look at the function push(). First of all, we are just creating a node and storing the address, in a pointer called new1.

    new1=(struct stack*)malloc(sizeof(struct stack));

    Then you have to make the new element (pointed to by the new1 pointer) the top-most one, and the previous element the next element.

    new1->next=top; top=new1;

    So we find that just by manipulating the next and the top pointers, you can add an element on top of the stack. In the same way, you can pop the values from the top by just re-assigning top by the value of next pointer (of the first element of the stack), and then releasing the memory for that element.

    new1=top; top=top->next; free(new1);

  • Programming in C Part II

    YM/SR/CPRG2/1.0 57

    Appreciating queue in C

    We have seen that stacks are ordered collection of items, where items are added and removed from the top. Queues also ordered collection of items, but it differs from the stack in the order of addition and removal of items. In queue, items are deleted from one end known as the front, and inserted from the other end known as the rear of the queue. Due to this nature, queues are also known as FIFO (First in First out) list. The following figure illustrates a queue:

    You must be asking this pertinent question at this point of time: Where do we apply this concept of queue? Generally, queues are used in applications where some kind of scheduling job is done. Operating Systems, that are mostly time-sharing in nature, use this concept to schedule the execution of applications. When a new program is to be executed, it is put at the end of the queue. The programs, which are at the beginning, are executed first. In real life scenario, you must have waited in a queue in front of the railway reservation counter.

    Appreciate queue in C

    Queues are ordered collection of items whereitems are added at the end of the queue, and theitems are removed from the front.

    Queue it is also termed as FIFO (First in Firstout list).

  • Programming in C Part II

    YM/SR/CPRG2/1.0 58

    Structures in C to represent queue

    Queues are also implemented in the same manner as stacks, in C. They only differ in the order of insertion and deletion of the constituent elements. We will be representing the queue with the help of linked list. struct queue { char itemno[5]; char itemdesc[30]; float rate; int qty; struct queue *next; }*new1,*front,*rear;

    You can notice that the structure is very similar to that of the node in a linked list. Just two pointers front and rear are declared to point to the front and rear of the queue, respectively.

    Structures in C to represent queue

    struct queue{char itemno[5];char itemdesc[30];float rate;int qty;struct queue *next;

    }*new1,*front,*rear;

  • Programming in C Part II

    YM/SR/CPRG2/1.0 59

    Insert and delete in queue

    In queue you can only insert at the end of the queue: #include #include struct queue { char itemno[5]; char itemdesc[30]; float rate; int qty; struct queue *next; }*new1,*front,*rear; char c; main() { char choice; choice='x'; front=NULL; rear=NULL; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert onto the Queue"); printf("\n D. Display the queue"); printf("\n Q. Quit"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { insert(); } if((choice=='D')||(choice=='d')) { remove1();

    Insert and delete in queue

    insert(){new1=(struct stack*)malloc(sizeof(struct queue));printf("\n Enter :");printf("\n\t Item No:\t");scanf("%s",new1->itemno);fflush(stdin);printf("\n\tDescription:\t");scanf("%s",new1->itemdesc);fflush(stdin);printf("\n\t Rate:\t");scanf("%f",&new1->rate);fflush(stdin);printf("\n\t Quantity:\t");scanf("%d",&new1->qty);if(rear==NULL){front=new1;}else{rear->next=new1;}rear=new1;c=getchar();}

  • Programming in C Part II

    YM/SR/CPRG2/1.0 60

    } } } insert() { new1=(struct stack*)malloc(sizeof(struct queue)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); if(rear==NULL) { front=new1; } else { rear->next=new1; } rear=new1; c=getchar(); } remove1() { new1=front; printf("Item Code: \t%s\n ",new1->itemno); printf("Description\t %s\n ",new1->itemdesc); printf("Rate%f\t\n ",new1->rate); printf("Quantity\t%d\n ", new1->qty); front=new1->next; if(front==NULL) { rear=NULL; } free(new1); c=getchar(); }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 61

    Consider the following code snippet. First we are creating a node and storing the address in a pointer called new1:

    new1=(struct stack*)malloc(sizeof(struct queue));

    If the queue is empty, the pointer front should point to the node, whose address is stored in the pointer new1. Otherwise if the queue exists, the next pointer of the last node (whose address is stored in the rear pointer), is assigned the address of the newly created node, i.e. new1. Nevertheless for both the cases, the pointer rear is assigned the address of the new node, i.e. new1.

    if(rear==NULL) { front=new1; } else { rear->next=new1; } rear=new1;

    Items can only be removed from the front of the queue. So first, the address of the node to be deleted, i.e. front, is stored in a pointer called new1. Then the pointer front is re-assigned the address of the second (next) node in the queue, pointed to by the next pointer of the node, whose address is stored in new1. Finally, node is physically deleted with the help of the library function, free().

    new1=front;

    printf("Item Code: \t%s\n ",new1->itemno); printf("Description\t %s\n ",new1->itemdesc); printf("Rate%f\t\n ",new1->rate); printf("Quantity\t%d\n ", new1->qty); front=new1->next; if(front==NULL) { rear=NULL; } free(new1);

  • Programming in C Part II

    YM/SR/CPRG2/1.0 62

    The concept of Binary trees

    In the previous chapters, we have learnt about the use of linked list (single and double) to implement data structures. We have also understood how it offers flexibility in comparison to arrays, in terms of dynamically adding or deleting items in a list. Though lists are very flexible in terms of addition and deletion of items, it suffers a major drawback in terms of the searching time. The searching in a linked list is linear i.e. the search-time is directly proportional to the size of the list. So if the size of the linked list is very large, the time required to search for a particular element is also longer. To do away with this inefficiency, we will discuss another data structure called binary tree. The main objective of this data structure is to reduce the search-time of an element. Now the big question is - what is this binary tree? A binary tree is a data structure, which represents data in inverted tree like structure. It contains a finite set of elements that is either empty or is partitioned into three disjoint subsets- Root, Left, and Right. It is generally used to represent data, which has some kind of hierarchical relationship among elements. The figure below depicts a binary tree containing the Item Code.

    The concept of Binary trees

    A binary tree is a data structure, which representsdata in inverted tree like structure.

    It contains a finite set of elements that is eitherempty or is partitioned into three disjoint subsets-Root, left and right.

    It is generally used to represent data, which hassome kind of hierarchical relationship amongelements.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 63

    From the figure given above, lets try to understand the concept of a binary tree. Each bubble in the figure is actually a node or a leaf. Each node has a data part and pointers (which stores the address of the nodes to which it points). The top most node in the tree is called the root. In the above figure, the node with the Item Code I010 is the root. Each node under a node is called subtree. For example, node with item code I002 is a subtree. A node with a subtree under it, is called a parent node. For example, the node with the item code I002 is the parent node of the node with item code I005 and I001. If a node has no subtree under it, then it is known as terminal node. For example, the node containing the item code I016 is a terminal node. Different types of binary tree Binary trees can be of different types. But we will be concentrating on the following two types of binary trees: Unbalanced binary tree

    Balanced binary tree

    Unbalanced binary tree In this type of binary tree, the heights of the subtrees are not equal. Although, each node can have a maximum of two subtrees, but it may not contain any node at all. This produces an unbalanced tree. The following figure depicts an unbalanced tree:

    I001

    I002

    I010

    I005

    I013

    I017

    I016 I019 I004

  • Programming in C Part II

    YM/SR/CPRG2/1.0 64

    Balanced binary tree In balanced binary tree, the numbers of nodes in both sides are balanced. That is the heights of the two subtrees are almost same. They can differ by one node, at most. The following figure depicts a balanced binary tree: In this chapter we will concentrate on the most popular form of binary tree, i.e. sorted binary tree. In a sorted binary tree all the nodes are arranged following a particular pattern. The pattern is that all the nodes having data larger than the data of the parent node is arranged on the right side of the tree.

    I001

    I002

    I010

    I005

    I003

    I000

    I001

    I002

    I010

    I005

    I013

    I016

    I015 I019 I004

  • Programming in C Part II

    YM/SR/CPRG2/1.0 65

    On the other hand, the nodes having data smaller than the data of the parent node are added on the left side of the tree. The following figures depicts a sorted binary tree: From the figure above you can see that the node with data larger than the parent (root) node, i.e. the node containing the data item I006, is added on the left of the root . The advantage that we get from sorted binary tree is that searching, insertion, and deletion becomes much faster. Though we have explained what is binary tree but still we have not answered the question - What is the application of binary tree? Binary tree is a very handy data structure when we require two-way decision making at different points of a process. It is also useful when we have to store or represent some kind of hierarchical data. For instance if you want to show the Unix file system, which is hierarchical in nature, then binary tree can be the best option.

    I005

    I006

    I010

    I008

    I0013

    I0019

    I0018 I0029I007

  • Programming in C Part II

    YM/SR/CPRG2/1.0 66

    Binary trees with structures in C

    In the course of studying C, we have already seen the implementation of several data structures. Binary tree is represented in a similar fashion as doubly linked list:

    struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *left; struct bill *right; }; struct bill *root;

    From the above code snippet you can find a resemblance with the doubly linked list. Conventionally the two pointers are named left and right, respectively. We have also declared another pointer called root. It will be used to store the address of the first node.

    Binary trees with structures in C

    struct bill{char itemno[5];char itemdesc[30];float rate;int qty;struct bill *left;struct bill *right;

    };struct bill *root;

  • Programming in C Part II

    YM/SR/CPRG2/1.0 67

    Insert node in binary tree

    We our concentrating on the discussion of sorted binary trees. Therefore, we will be discussing insertion in a sorted binary tree. Like any other sorted structure, in binary sorted tree we first have to compare the data part of the newly created node with the data part of the existing nodes. This is required to insert the node in the appropriate place. After working with linked lists it is sure that you are not to be told that, to insert a new node first of all you have to create the node by allocating memory to it. After that, you have to change the left and right pointer of the node accordingly, under which the new node will be added. Lets look into the figure given below and try to understand it:

    An existing binary tree

    I005 120 110

    left Data right

    Root 100

    I003 NULL NULL

    left Data right

    110

    I009 NULL NULL

    left Data right

    120

    Insert node in binary tree

    in binary sorted tree, first we have to compare the datapart of the newly created node with the data part of theexisting nodes. This is required to insert the node inthe appropriate place.

    I005 120110

    left Data right

    Root100

    I003 NULLNULL

    left Data right

    110

    I009 NULLNULL

    left Data right

    120

    I016 NULLNULL

    left Data right

    130

  • Programming in C Part II

    YM/SR/CPRG2/1.0 68

    A node has to be inserted

    A question might have spawned in your mind: How I will know where to add the newly created node? From the figure given above, it is clear that the Item code in the newly created node is I016, which is greater than the Item code of the root node. So it will be added to the right side of the root node. Again under the root there is another node whose item code is less than the item code of the newly created node. So the new node will move to right side of that node. In the right side of the node with the item code I009, there is no other node. So the newly created node will to be added to the right pointer of this node. As a result we have to place a pointer say prev on the node with the item code I009. The following code places the pointer on the appropriate node:

    struct bill *find(struct bill *neo) {

    struct bill *ptr,*prev; ptr=root; while(ptr) { if((strcmp(neo->itemno,ptr->itemno))>0) { prev=ptr; ptr=ptr->right; } else { if((strcmp(neo->itemno,ptr->itemno))

  • Programming in C Part II

    YM/SR/CPRG2/1.0 69

    { prev=ptr; ptr=ptr->left; } else { prev=NULL; ptr=NULL; } } }

    return prev;

    }

    From the above code, you can find that we have taken two pointers, i.e. ptr and prev. The pointer ptr is assigned the address stored by the pointer root. A loop is started, which continues until it encounters NULL. Inside the loop we are comparing the data part of the newly created node with the data of the node pointed to by the pointer ptr. If the value contained in the data part of the newly created node is greater than the node pointed to by the ptr, then it is advanced towards the right of the list. Otherwise, it is advanced towards the left of the list. Whether the ptr is advanced to the right or the left of the list, the pointer prev is made to follow the pointer ptr.

    I005 120 110

    left Data right

    Root 100

    I003 NULL NULL

    left Data right

    110

    I009 NULL NULL

    left Data right

    120

    I016 NULL NULL

    left Data right

    130

    NULL

    ptr

    120 prev

  • Programming in C Part II

    YM/SR/CPRG2/1.0 70

    Once the pointer prev is positioned appropriately, it is returned to the caller. Now lets look into the caller function, which actually adds the newly created node to the list.

    add() { struct bill *createnode(),*new,*prev1,*find(); new=createnode(); if(root==NULL) { root=new; } else { prev1=find(new); if(prev1!=NULL) { if((strcmp(new->itemno,prev1->itemno))>0) { prev1->right=new; } else { prev1->left=new; } } else { printf("\nThe Item code already exists\n"); } } }

    Let's try to understand the code. First of all we are checking whether the root is NULL or not. If the root is NULL, it means the tree is empty. Therefore, we are straightway assigning the address of the newly created node to the root. Otherwise we are calling the function find() to get the pointer pointing to the node where the newly created node has to be added.

    Once we get the pointer, again we are checking the data part of the newly created node with that of that node under which it will be added. If the data part of the newly created node is greater than the node pointed to by the prev, we are assigning the address of the newly created node to the right pointer of the node pointed to by the prev. Otherwise if it is less, then we are assigning the address of the newly created node to the left pointer of the node pointed to by the prev.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 71

    if((strcmp(new->itemno,prev1->itemno))>0) { prev1->right=new; } else {

    prev1->left=new; }

    If we combine the code, it will be like this:

    #include #include struct bill { char itemno[5]; char itemdesc[30]; float rate; int qty; struct bill *left; struct bill *right; }; char c; struct bill *root; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the Binary tree"); printf("\n Q. Quit"); printf("\n Enter your choice :\t"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='Q')||(choice=='q')) { exit(); } } }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 72

    add() { struct bill *createnode(),*new,*prev1,*find(); new=createnode(); if(root==NULL) { root=new; } else { prev1=find(new); if(prev1!=NULL) { if((strcmp(new->itemno,prev1->itemno))>0) { prev1->right=new; } else { prev1->left=new; } } else { printf("\nThe Item code already exists\n"); } } } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); } struct bill *find(struct bill *neo) { struct bill *ptr,*prev; ptr=root; while(ptr)

  • Programming in C Part II

    YM/SR/CPRG2/1.0 73

    { if((strcmp(neo->itemno,ptr->itemno))>0) { prev=ptr; ptr=ptr->right; } else { if((strcmp(neo->itemno,ptr->itemno))left; } else { prev=NULL; ptr=NULL; } } } return prev; }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 74

    Traversing a binary tree

    To traverse a sorted binary tree, the best possible solution is to take the help of recursion. You have already learnt about recursive functions. So there is no need to explain recursion again. We will be traversing and at the same time displaying the information of a sorted binary tree. We know that in a sorted binary tree, the smallest data is stored in the leftmost node of the tree. So we will start displaying the data from the leftmost node. Lets understand this with the help of an example. Say, the binary tree is somewhat like this: So the task before us is to display the items of this tree. The data should be shown like this: I003 I005 I009

    I005 120 110

    left Data right

    Root 100

    I003 NULL NULL

    left Data right

    110

    I009 NULL NULL

    left Data right

    120

    Traverse a binary tree

    We can traverse a binary tree with recursion.

    show(struct bill *ptr){ if(!ptr){return;}show(ptr->left);printf("%s\t ",ptr->itemno);printf("%s\t ",ptr->itemdesc);printf("%f\t ",ptr->rate);printf("%d\t\n ",ptr->qty);show(ptr->right);}

  • Programming in C Part II

    YM/SR/CPRG2/1.0 75

    Now the question is how to achieve this? show(struct bill *ptr) { if(!ptr) { return; } show(ptr->left); printf("%s\t ",ptr->itemno); printf("%s\t ",ptr->itemdesc); printf("%f\t ",ptr->rate); printf("%d\t\n ",ptr->qty); show(ptr->right); }

    From above code snippet, you can find that the function is recursive in nature. The pointer ptr passed to this function initially contains the address of the root. The first instruction is:

    show(ptr->left); This is an instruction to traverse the left subtree of the root. This will continue until and unless it meets a NULL pointer. So in our example, the traversal starts from the node containing the data I005. Then it traverses the left subtree. Now ptr points to the node with data I003. After that it traverses left and encounters a NULL value, since it is not having any subtree, and I003 is displayed. After this it encounters the statement:

    show(ptr->right); Therefore it traverses to the right subtree. Since the pointer ptr is pointing to the node with data I003, so on traversing right, it encounters a NULL pointer. Therefore, it returns. Since the traversal of both the left and the right subtree is complete, with ptr pointing to the node containing the data I003, it now returns to the node containing the data I005. The traversal is not yet complete. It will first print I005. Then it will traverse the right subtree. ptr will now point to the node containing the data I009. Again it will move to the left subtree. Once again the same sequence will be followed as discussed earlier. And it will print I009. So the complete code will be like this: #include #include struct bill { char itemno[5];

  • Programming in C Part II

    YM/SR/CPRG2/1.0 76

    char itemdesc[30]; float rate; int qty; struct bill *left; struct bill *right; }; char c; struct bill *root; main() { char choice; choice='x'; while((choice!='q')&&(choice!='E')) { system("tput clear"); printf("\n\n I. Insert into the Binary tree"); printf("\n D. Display the Binary tree"); printf("\n Q. Quit"); printf("\n Enter your choice :\t"); choice=getchar(); fflush(stdin); if((choice=='I')||(choice=='i')) { add(); } if((choice=='D')||(choice=='d')) { display(); } if((choice=='Q')||(choice=='q')) { exit(); } } } add() { struct bill *createnode(),*new,*prev1,*find(); new=createnode(); if(root==NULL) { root=new; } else { prev1=find(new); if(prev1!=NULL) { if((strcmp(new->itemno,prev1->itemno))>0) {

  • Programming in C Part II

    YM/SR/CPRG2/1.0 77

    prev1->right=new; } else { prev1->left=new; } } else { printf("\nThe Item code already exists\n"); } } } display() { struct bill *ptr; ptr=root; show(ptr); } struct bill *createnode() { struct bill *new1; new1=(struct bill*)malloc(sizeof(struct bill)); printf("\n Enter :"); printf("\n\t Item No:\t"); scanf("%s",new1->itemno); fflush(stdin); printf("\n\tDescription:\t"); scanf("%s",new1->itemdesc); fflush(stdin); printf("\n\t Rate:\t"); scanf("%f",&new1->rate); fflush(stdin); printf("\n\t Quantity:\t"); scanf("%d",&new1->qty); return(new1); } struct bill *find(struct bill *neo) { struct bill *ptr,*prev; ptr=root; while(ptr) { if((strcmp(neo->itemno,ptr->itemno))>0) { prev=ptr; ptr=ptr->right; }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 78

    else { if((strcmp(neo->itemno,ptr->itemno))left; } else { prev=NULL; ptr=NULL; } } } return prev; } show(struct bill *ptr) { if(!ptr) { return; } show(ptr->left); printf("%s\t ",ptr->itemno); printf("%s\t ",ptr->itemdesc); printf("%f\t ",ptr->rate); printf("%d\t\n ",ptr->qty); show(ptr->right); }

  • Programming in C Part II

    YM/SR/CPRG2/1.0 79

    Deletion of a Node from Binary tree

    The deletion of a node from a binary tree is not very different from the deletion of a node from the doubly linked list. It is all a game of pointer manipulation. Since the organizing of the data is different in case of binary tree as compared to doubly linked list, there will be certain changes in pointer manipulation. Let's try to understand it with the help of an example.

    Consider the binary tree depicted in the diagram above. Whenever we are deleting any node from the above tree, we have to link the left and the right subtree accordingly. Otherwise, all the information will be lost. Depending upon the position of the node that we are deleting there can be several situations of deletion. Situation 1: Deletion of a terminal node, which has no subtrees, e.g. I009

    I001

    I002

    I010

    I005

    I003

    I007

    I006 I009 I004

    Deletion of a Node from Binary tree

    Deletion of a node in binary tree is very similar todeletion in doubly linked list.

    Deletion from binary tree has several scenarios Deletion of a terminal node, which has no

    subtrees Deletion of a node, which has only one subtree Deletion of a node, which has both subtrees. The root node is being deleted.

  • Programming in C Part II

    YM/SR/CPRG2/1.0 80

    Since, I009 is the terminal node on right side, therefore the right pointer of its parent node (i.e. I007) has to be initialized to NULL. If the terminal node happens to be the left node, then the left pointer should be initialized to NULL. Situation 2: Deletion of a node, which has only one subtree, e.g. I005 In this situation depending upon the position of the node i.e. left or right, the left or the right pointer of the parent node of the deleted one should point to the left/right subtree of the deleted node.

    Situation 3: Deletion of a node, which has both subtrees, e.g. I002

    In this situation both the left and the right pointers of the parent node of the deleted node has to be linked to the subtrees of the node being deleted.

    I001

    I002

    I010

    I003

    I007

    I006 I009 I005

    I001

    I002

    I010

    I003

    I002 I009 I007

  • Programming in C Part II

    YM/SR/CPRG2/1.0 81

    Situation 4: The root node is being deleted. It is very similar to other cases of deletion. The only difference is that the root pointer has to be updated. Once we have seen the different situations now lets look at a function implementing them: void del() { char rep='y'; char mempno[5]; if(root==NULL) return; while(rep=='y') { printf("\nEnter Empno to delete :"); scanf("%s",mempno); fflush(stdin); ptr=root; pptr=search1(ptr,mempno); if(pptr!=NULL) { root=delet(ptr,mempno); } else { printf("\nNo such Node"); } printf("\nWish to continue:");scanf("%c",&rep);fflush(stdin); } } struct tree *delet(struct tree *p