C++ Programs for Computer Science Students

download C++ Programs for Computer Science Students

If you can't read please download the document

description

C++ Programs for Computer Science Students, C++, Computer Science, Binary search Tree, Matrix Operation

Transcript of C++ Programs for Computer Science Students

  • 1

    1 IMPLEMENTATION OF CIRCULAR QUEUE

    OBJECTIVE: Here we have implemented a program to implement a circular queue using linear array.

    ALGORITHM: ENQUEUE(QUEUE, FRONT, REAR,ITEM)

    This procedure inserts an element ITEMinto the queue.

    1. [Queue is already filled?]

    If FRONT=1 and REAR = N or FRONT = REAR + 1, then :

    Write: OVERFLOW and Return.

    2. [Find new value of REAR.]

    If FRONT = NULL, then : [Queue initially empty.]

    Set FRONT = 1 and REAR = 1.

    Else :

    Set REAR = [ REAR + 1 ] MOD N.

    [End of if structure.]

    3. Set QUEUE[REAR]=ITEM. [Inserts new element.]

    4. Return.

    DEQUEUE(QUEUE,FRONT, REAR, ITEM) This procedure deletes the front element of queue.

    1. [ Queue already empty?]

    If FRONT = NULL, then :

    Write: UNDERFLOW and Return.

    2. Set ITEM = QUEUE[ FRONT ].

    3. [Find new value of FRONT.]

    If FRONT = REAR, then : [Queue has only one element to start.]

    Set FRONT = NULL and REAR = NULL.

    Else : Set FRONT = [ FRONT + 1 ] MOD N.

    [End of if structure.]

    4. Return ITEM.

    CODE: #include

    #include

    #define MAX 10

    class queue{

    intqu[MAX];

    int front;

  • 2

    int rear;

    public:

    void insert(int);

    intqdelete();

    void display();

    intisfull();

    intisempty();

    queue() {

    front=rear=-1;

    }

    };

    int queue::isfull()

    {

    if(((front==0)&&(rear==MAX-1))||(front==rear+1))

    return 1;

    else

    return 0;

    }int queue::isempty()

    {

    if(front==-1)

    return 1;

    else

    return 0;

    }

    void queue::insert(int item)

    {

    if(front==-1) /* Adjust rear */

    front=rear=0;

    else

    rear=(rear+1)%MAX;

    qu[rear]=item; /* Store element at new rear */

    }

    int queue::qdelete()

    {

    int item;

    /* Store front in temporary variable */

    item=qu[front];

    if(front==rear) /* Adjust front */

    front=rear=-1;

    else

    front=(front+1)%MAX;

    return item; /* return deleted element */

    }

    void queue::display(){

    if(isempty())

    cout

  • 3

    }

    int main()

    {

    queue q;

    intch, item;

    cout

  • 4

    Enter Your choice : 1

    Entervalue : 5

    The queue is : 5

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 1

    Entervalue : 6

    The queue is : 5 6

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 1

    Entervalue : 7

    The queue is : 5 6 7

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 1

    Entervalue : 8

    The queue is : 5 6 7 8

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

  • 5

    Enter Your choice : 2

    5 is deleted.

    The queue is : 6 7 8

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 2

    6 is deleted.

    The queue is : 7 8

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 2

    7 is deleted.

    The queue is : 8

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 2

    8 is deleted.

    Queue is empty.

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

  • 6

    Enter Your choice : 2

    Queue empty.

    Options available

    ---------------------

    1. Insert element into queue.

    2. Delete element from queue.

    3. Exit.

    Enter Your choice : 3

    Press any key to continue

    DISCUSSION: 1. A queue, also called a First-In-First-Out (FIFO) system, is a linear list in which deletions can

    take place only at one end called the front, and insertion can take place at the other end

    called the rear.

    2. In this program the queue can store integer type of data only.

    3. The term circular comes from the fact that we assume that QUEUE[1] comes after

    QUEUE[N] in the array.

  • 7

    2 MERGE SORT AND BINARY SEARCH

    OBJECTIVE: Here we have implemented Merge Sort to sort an array in ascending order and then to search an

    element from the sorted array using Binary Search.

    ALGORITHM:

    ALGORITHM FOR BINARY SEARCH:

    BINARYSEARCH (LIST, BEG, END, ITEM)

    Here LIST is a sorted array with lower bound BEG and upper bound END. ITEM is a given item of

    information. The variable MID is the middle location of a segment of elements of LIST. This

    algorithm finds and returns the location of ITEM in LIST or returns -1.

    1. [Initialize segment variable.] Set MID=-1.

    2. If BEG>END, then:

    Return MID.

    Else:

    Repeat Steps 3 to 4.

    3. MID=(BEG+END)/2.

    4. If LIST[MID]=ITEM, then:

    Return MID.

    Else If LIST[MID]>ITEM, then:

    Call BINARYSEARCH(LIST,BEG,MID-1,ITEM).

    Else:Call BINARYSEARCH(LIST,MID+1,END,ITEM).

    [End of If structure.]

    [End of If structure.]

    5. Exit.

    ALGORITHM FOR MERGE SORT:

    MERGESORT( A, LB, UB )

    This algorithm sorts the N-element array A using merge sort. LB and UB are respectively the lower

    and upper bound of the array A.

    1. If LB

  • 8

    MERGESUBARRAY( A,LB,LE,RB,RE )

    Here A is a linear array, variable LB and LE represents the beginning and ending index of the left sub

    array and RB and RE represents the beginning and ending index of right sub array. This algorithm

    merges these two sub arrays. It uses local variables NA, NB as counters to keep track of the elements

    of left and right sub array respectively. We use a temporary array C. NC keeps track of the index of

    the array C.

    1. [ Initialize. ] Set NA = LB, NB = RB, NC = LB.

    2. Repeat while NA

  • 9

    void display() {

    for(int i=0;i

  • 10

    }

    };

    int main()

    {

    intx,loc,ch,it;

    floatft;

    charct;

    search i;

    search f;

    search c;

    cout

  • 11

    if(loc==-1)

    cout

  • 12

    3. Sort n Search on a character array.

    4. Exit.

    Enter your choice : 1

    Enter no. of elements in the list : 6

    Enter elements for the list :

    12

    65

    -9

    0

    8

    31

    You have entered the list as :

    12 65 -9 0 8 31

    The Sorted list is :

    -9 0 8 12 31 65

    Enter element to be searched : 31

    Location of 31 = 4

    SELECT ONE:

    -----------------

    1. Sort n Search on an integer array.

    2. Sort n Search on a float array.

    3. Sort n Search on a character array.

    4. Exit.

    Enter your choice : 2

    Enter no. of elements in the list : 5

    Enter elements for the list :

    2.36

    5.47

    -0.12

    2.47

    0.12

    You have entered the list as :

    2.36 5.47 -0.12 2.47 0.12

    The Sorted list is :

    -0.12 0.12 2.36 2.47 5.47

    Enter element to be searched : 6.55

  • 13

    6.55 not found.

    SELECT ONE:

    -----------------

    1. Sort n Search on an integer array.

    2. Sort n Search on a float array.

    3. Sort n Search on a character array.

    4. Exit.

    Enter your choice : 3

    Enter no. of elements in the list : 8

    Enter elements for the list :

    A

    S

    D

    P

    M

    T

    H

    R

    You have entered the list as :

    A S D P M T H R

    The Sorted list is :

    A D H M P R S T

    Enter element to be searched : P

    Location of P = 4

    SELECT ONE:

    -----------------

    1. Sort n Search on an integer array.

    2. Sort n Search on a float array.

    3. Sort n Search on a character array.

    4. Exit.

    Enter your choice : 6

    Exception detected : Wrong Input.

    SELECT ONE:

    -----------------

    1. Sort n Search on an integer array.

    2. Sort n Search on a float array.

    3. Sort n Search on a character array.

    4. Exit.

  • 14

    Enter your choice : 4

    Press any key to continue

    DISCUSSION:

    1. Binary search is a search technique that is applied to a list of ordered keys. At each step of the search,

    the list is partitioned into two equal parts, with the selection of the appropriate partition to probe in

    the next iteration made on the basis of relative key values.

    2. To execute the search properly, the array must be sorted. After taking values to the array the

    program itself sorts the list in ascending order using merge sort. Thus it is not compulsory for the

    user to provide input in sorted order.

    3. This program searches an element from an array of integers in recursive way.

    4. This program is implemented on generic data types using a template class.

  • 15

    3 POLYNOMIAL ADDITION

    OBJECTIVE: We have implemented a C++ program toperform the addition of two polynomials.

    ALGORITHM: POLYNOMIALADDITION( POLY1, POLY2, POLY3, COEF, POWR, NEXT )

    This algorithm adds two polynomials POLY1, POLY2 and Save the result as POLY3. Each

    polynomial node contains a COEF, i.e. the coefficient of the term, a POWR, i.e. the power of the

    power of the term and a NEXT that holds the address of the next node.

    1. Repeat Step to while POLY1 NULL and POLY3 NULL :

    2. If POLY1 [ POWR ] > POLY2 [ POWR ], then :

    POLY3 [ COEF ] = POLY1 [ COEF ].

    POLY3 [ POWR ] = POLY1 [ POWR ].

    POLY3 = POLY3 [ NEXT ].

    3. Else if POLY1 [ POWR ] < POLY2 [ POWR ], then :

    POLY3 [ COEF ] = POLY1 [ COEF ].

    POLY3 [ POWR ] = POLY1 [ POWR ].

    POLY3 = POLY3 [ NEXT ].

    4. Else :

    POLY3 [ COEF ] = POLY1 [ COEF ] +POLY2 [ COEF ].

    POLY3 [ POWR ] = POLY1 [ POWR ].

    POLY3 = POLY3 [ NEXT ].

    [ End of If Structure. ]

    5. If POLY [ COEF ] 0, then :

    Add POLY3 to resultant list.

    [ End of If Structure. ]

    [ End of loop. ]

    6. Add nodes left in 1st polynomial to resultant list.

    7. Add nodes left in 2nd polynomial to resultant list.

    8. Return.

    CODE: #include

    #include

    typedef class node

    {

    public:

    floatcoeff;

  • 16

    int power;

    class node *next;

    } node;

    class polynomial

    {

    node *poly;

    public:

    voidreadnode(node **);

    void display(node *);

    void sort(node **);

    voidaddpoly(node**,node*,node*);

    voidaddnode(node **,float,int);

    polynomial()

    {

    poly=NULL;

    }

    };

    void polynomial::readnode(node **head)

    {

    *head=new node; /* Create a new node */

    charch;

    float c;

    int p;

    coutc;

    coutp;

    (*head)->power=p;

    (*head)->coeff=c; /* Assign value to the new node */

    coutch;

    if(ch=='N'||ch=='n')

    (*head)->next=NULL;

    else

    readnode(&(*head)->next); /* Create the next node */

    return;

    }

    void polynomial::sort(node **root)

    {

    node *curr,*save,*pre;

    floattempc;

    inttempp;

    for(curr=*root;curr->next!=NULL;curr=curr->next)

    {

    for(save=curr->next;save!=NULL;save=save->next)

    {

    if(curr->powerpower)

    {

    pre=save;

    tempc=curr->coeff;

    tempp=curr->power;

    curr->coeff=save->coeff;

  • 17

    curr->power=save->power;

    save->coeff=tempc;

    save->power=tempp;

    }

    }

    }

    }

    void polynomial::display(node *poly)

    {

    node *ptr;

    ptr=poly;

    if(ptr==NULL)

    {

    coutnext;

    else

    {

    if(ptr->coeff>0)

    coutcoeff==1)

    cout

  • 18

    temp=new node;

    temp->coeff=coef;

    temp->power=pwr;

    if(*ptr==NULL)

    {

    temp->next=NULL;

    *ptr=temp;

    }

    else

    {

    temp->next=*ptr;

    *ptr=temp;

    }

    }

    void polynomial::addpoly(node **list3,node *list1,node *list2)

    {

    floatcoef;

    intpwr;

    while((list1!=NULL)&&(list2!=NULL))

    {

    if(list1->power>list2->power)

    { /* If of larger power add to new list and move to next node */

    coef=list1->coeff;

    pwr=list1->power;

    list1=list1->next;

    }

    else if(list2->power>list1->power)

    {

    coef=list2->coeff;

    pwr=list2->power;

    list2=list2->next;

    }

    else if(list2->power==list1->power)

    { /* If of same power add the coefficients */

    coef=list1->coeff+list2->coeff;

    pwr=list1->power;

    list1=list1->next;

    list2=list2->next;

    }

    if(coef!=0)

    addnode(list3,coef,pwr); /* Add the resultant node to new list */

    }

    if(list1==NULL)

    { /* If more nodes left in 1st polynomial add them in new list */

    while(list2!=NULL)

    {

    addnode(list3,list2->coeff,list2->power);

    list2=list2->next;

    }

    }

  • 19

    if(list2==NULL)

    { /* If more nodes left in 2nd polynomial add them in new list */

    while(list1!=NULL)

    {

    addnode(list3,list1->coeff,list1->power);

    list1=list1->next;

    }

    }

    }

    int main()

    {

    polynomial p;

    node *poly1=NULL,*poly2=NULL,*poly3=NULL;

    cout

  • 20

    Want to add more nodes[Y/N]...y

    Enter Coefficient : -1

    Enter Power : 4

    Want to add more nodes[Y/N]...y

    Enter Coefficient : 2

    Enter Power : 0

    Want to add more nodes[Y/N]...n

    Enter 2nd Polynomial :

    Enter Coefficient : 7

    Enter Power : 5

    Want to add more nodes[Y/N]...y

    Enter Coefficient : -2

    Enter Power : 3

    Want to add more nodes[Y/N]...y

    Enter Coefficient : 1

    Enter Power : 2

    Want to add more nodes[Y/N]...y

    Enter Coefficient : 3

    Enter Power : 0

    Want to add more nodes[Y/N]...n

    1st Polynomial : + 2x^5 -x^4 + 5x^3 + 2

    2nd Polynomial : + 7x^5 -2x^3 + x^2 + 3

    Sum of Polynomial : + 9x^5 -x^4 + 3x^3 + x^2 + 5

    Press any key to continue

  • 21

    DISCUSSION: 1. Here the linked list that is used to represent a polynomial contains one coefficient part, a

    power part and an address part to hold the address of next node.

    2. Above program takes input of coefficient and power separately of 2 different polynomials

    add them up to a new polynomial.

    3. If user enters the term not maintaining the decreasing order of power, the program itself can

    sort the terms in decreasing order of power.

  • 22

    4 FUNCTION OVERLOADING

    OBJECTIVE: We have implemented a C++ program to implement an overloaded function to perform different

    tasks.

    ALGORITHM: Here we have used the function ADD to perform different operations with different datatypes.

    ADDITION OF TWO INTEGERS:

    ADD(N1,N2, SUM)

    Here N1 AND N2 are two integers. This algorithm adds the two numbers and returns the sum as

    SUM.

    1. Set SUM = N1 + N2.

    2. Return SUM.

    3. Exit.

    ADDITION OF THREE INTEGERS:

    ADD ( N1, N2, N3 SUM )

    Here N1, N2 AND N3 are three integers. This algorithm adds the three numbers and returns the sum

    as SUM.

    1. Set SUM = N1 + N2 + N3.

    2. Return SUM.

    3. Exit.

    ADDITION OF A INTEGER AND A FLOAT:

    ADD (I,F, SUM )

    Here Iis an integer AND F is a float. This algorithm adds the two numbers and returns the sum as

    SUM.

    1. Set SUM =I + F.

    2. Return SUM.

    3. Exit.

    CONCATENATION OF TWO CHARACTERS:

    ADD ( C1, C2, NEWSTR )

    Here C1 AND C2 are two characters. This algorithm concatenates the two characters and returns the

    new string as NEWSTR.

    1. Set NEWSTR[ 0 ] = C1.

    2. Set NEWSTR[ 1 ] = C2.

    3. Set NEWSTR[ 3 ] = NULL.

    4. Return NEWSTR.

    5. Exit.

  • 23

    CONCATENATION OF TWO STRINGS:

    ADD ( S1, S2, NEWSTR )

    Here S1 AND S2 are two strings. This algorithm concatenates the two strings and returns the new

    string as NEWSTR.

    1. Set NEWSTR= S1.

    2. Set append S2 in NEWSTR.

    3. Return NEWSTR.

    4. Exit.

    ADDITION OF THE ASCII VALUE OF THREE CHARACTERS:

    ADD (C1,C2, C3 SUM )

    Here C1, C2 AND C3 are three characters. This algorithm adds the ASCII values of the characters

    and returns the sum as SUM.

    1. Set A1 = ASCII value of C1.

    2. Set A2 = ASCII value of C2.

    3. Set A3 = ASCII value of C3.

    4. Set SUM = A1 + A2 + A3.

    5. Return SUM.

    6. Exit.

    CODE: #include

    #include

    using namespace std;

    /* Function prototypes */

    void add(int,int);

    void add(int,int,int);

    float add(int,float);

    int add(float,int);

    int add(char,char,char);

    string add(char,char);

    string add(string,string);

    /* add() for adding two integers */

    void add(int x, int y)

    {

    int s=x+y;

    cout

  • 24

    /* add() for concatenate two characters */

    string add(char x, char y)

    {

    char z[3]={'\0'};

    string s;

    z[0]=x;

    z[1]=y;

    s=z;

    cout

  • 25

    coutq;

    add(p,q);

    cout

  • 26

    return(0);

    break;

    default:

    cout

  • 27

    Enter your choice : 3

    Enter integer : 12

    Enter float : 150.98

    A = 12

    B = 150.98

    Sum = 162.98

    1. Add two integers.

    2. Add three integers.

    3. Add a integer and a float.

    4. Concat two characters.

    5. Concat two strings.

    6. Add ASCII value of three characters.

    7. Exit.

    Enter your choice : 4

    Enter 1st character : S

    Enter 2nd character : A

    1st Character : S

    2nd Character : A

    After Concatenation : SA

    1. Add two integers.

    2. Add three integers.

    3. Add a integer and a float.

    4. Concat two characters.

    5. Concat two strings.

    6. Add ASCII value of three characters.

    7. Exit.

    Enter your choice : 5

    Enter 1st string : STRING

    Enter 2nd string : ARRAY

    1st String : STRING

    2nd String : ARRAY

    After Concatenation : STRINGARRAY

    1. Add two integers.

    2. Add three integers.

    3. Add a integer and a float.

    4. Concat two characters.

    5. Concat two strings.

    6. Add ASCII value of three characters.

    7. Exit.

    Enter your choice : 6

    Enter 1st character : S

    Enter 2nd character : A

    Enter 3rd character : P

    1st Character : S (83)

    1st Character : A (65)

  • 28

    1st Character : P (80)

    Sum of ASCII = 228

    1. Add two integers.

    2. Add three integers.

    3. Add a integer and a float.

    4. Concat two characters.

    5. Concat two strings.

    6. Add ASCII value of three characters.

    7. Exit.

    Enter your choice : 8

    Wrong Input.

    1. Add two integers.

    2. Add three integers.

    3. Add a integer and a float.

    4. Concat two characters.

    5. Concat two strings.

    6. Add ASCII value of three characters.

    7. Exit.

    Enter your choice : 7

    Press any key to continue

    DISCUSSION: 1. Using the concept of function overloading, we can design a family of functions with one function

    name but with different argument lists.

    2. Here we have used overloaded function add() to perform different operations with integers, floats,

    characters and strings, using them as arguments.

    3. The function would perform different operations depending on the argument list in the function call.

    4. The correct function to be invoked is determined by checking the number and type of the arguments

    but not on the function type.

  • 29

    5 INHERITANCE, VIRTUAL FUNCTION AND ABSTRACT CLASS

    OBJECTIVE: We have implemented a C++ program to illustrate inheritance, virtual function and abstract class.

    ALGORITHM: 1. Create a class shape with two protected variables D1 an D2 and two public member

    functions get_data() and display().

    2. Make display() as a pure virtual function.

    3. Create three more classes triangle, rectangle and cylinder.

    4. These three new classes are derived from class shape.

    5. Input base of triangle in D1 and height of triangle in D2.

    6. [ Calculate Area of triangle. ]

    Set Area = ( D1 + D2 ) / 2.

    Display components of triangle by redefining display().

    7. Input height of rectangle in D1 and width of rectangle in D2.

    8. [ Calculate Area of rectangle. ]

    Set Area = D1 * D2.

    Display components of rectangle by redefining display().

    9. Input radius of cylinder in D1 and height of cylinder in D2.

    10. [ Calculate Area of triangle. ]

    Set Area = ( D1 + D2 ) / 2.

    Display components of cylinder by redefining display().

    11. Exit.

    CODE: #include

    #define pi 3.14

    class shape /* This is an abstract class */

    {

    protected:

    double d1,d2;

    public:

    voidget_data(double,double);

    virtual void display()=0; /* Pure virtual function definition */

    };

    /* derived classes */

    classtriangle:public shape

    {

  • 30

    double area;

    public:

    void calculate()

    {

    this->area=(d1*d2)/2; /* Use of this pointer */

    }

    void display() /* Redefinition of display() function */

    {

    cout

  • 31

    int main()

    {

    triangle t;

    rectangle r;

    cylinder c;

    doublea,b;

    cout

  • 32

    Area = 56

    +++++++++Enter data for cylinder+++++++++

    Enter value for radius : 5

    Enter value for height : 7

    Base = 5

    Height = 7

    Area = 549.5

    Press any key to continue

    DISCUSSION: 1. We have used this pointer to access the variable area in the class triangle and cylinder. The pointer

    this acts as an implicit argument to all the member functions. The same operation can be performed

    without using this as in class rectangle.

    2. The function display() in the base class shape is defined as a pure virtual function and is redefined in

    all the derived classes.

    3. As the shape contains the pure virtual function display() and no object of shape is created yet, shape

    is an abstract base class. The main objective of an abstract base class is to provide some traits to

    derived classes and create a base pointer required for achieving runtime polymorphism.

  • 33

    6 QUICKSORT ON AN ARRAY OF STRINGS : MANIPULATING STRINGS

    OBJECTIVE: Here we have implemented quick sort to sort an array of strings to sort them in dictionary order.

    ALGORITHM: QUICKSORT (A, LB, UB)

    This algorithm sorts the N-element array A using quicksort. LB and UB are respectively the lower

    and upper bound of the array A.

    1. If LB>=UB, then:

    Return.

    Else :

    (a) Call PARTITION ( A, LB, UB, LOC ).

    (b) Call QUICKSORT (A, LB, LOC - 1).

    (c) Call QUICKSORT (A, LOC+1, UB).

    [End of If structure.]

    Exit.

    PARTITION(A,BEG,END,LOC)

    Here A is a linear array, BEG and END represents lower and upper bound of the array. This

    algorithm finds the proper position of the element in the location LOC in the array.

    1. [ Initialize. ] Set LEFT = BEG, RIGHT = END, LOC = BEG.

    2. Repeat Step 3 to 7 while LOC LEFT or LOC RIGHT :

    3. Repeat while A[ LOC ]A[ RIGHT ], then:

    Interchange A[ LOC ] and A[ RIGHT ].

    Set LOC = RIGHT.

    [ End of If structure. ]

    5. If LOC RIGHT, then :

    6. Repeat while A[ LOC ] >= A[ LEFT ] and LOC LEFT :

    Set LEFT = LEFT + 1.

    [ End of Step 6 loop. ]

    7. If A[ LOC ] < A[ LEFT ], then:

    Interchange A[ LOC ] and A[ LEFT ].

    Set LOC = LEFT.

    [ End of If structure. ]

  • 34

    [ End of If structure. ]

    [ End of Step 2 loop. ]

    8. Exit.

    CODE: #include

    #include

    using namespace std;

    #define MAX 80

    void partition(string *A,intbeg,int end, int *loc)

    {

    stringpivot,temp;

    intleft,right;

    *loc=left=beg;

    right=end;

    while(*loc!=left||*loc!=right)

    {

    while((A[*loc]0) /* if A[loc]>A[right] interchange these elements */

    {

    temp=A[*loc];

    A[*loc]=A[right];

    A[right]=temp;

    }

    if(*loc!=right)

    while((A[*loc]>=A[left])&&(*loc!=left)) /* Scan elements from left */

    left++;

    x=A[*loc].compare(A[left]);

    if(x

  • 35

    char temp[MAX],c;

    int n=0,i,flag=1;

    cout

  • 36

    DISCUSSION:

    1. Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two

    smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort

    the sub-lists. 2. Each recursive call to this quicksort function reduces the size of the array being sorted by at

    least one element, since in each invocation the element at pivotis placed in its final position.

    Therefore, this algorithm is guaranteed to terminate after at most n recursive calls. However,

    since partition reorders elements within a partition, this version of quicksort is not a stable

    sort. 3. This program sorts an array of strings. We have used the string classand its member

    functions and operators provided by C++ to manipulatethe strings instead of using a

    character array.

  • 37

    7 TRANSFORMATION OF INFIX TO

    PREFIX EXPRESSION

    AND PARENTHESIS CHECKER

    OBJECTIVE: We have implemented a C++ program to transform an infix expression into an equivalent prefix

    expression.

    ALGORITHM: INFIXTOPREFIX ( Q, P, STACK )

    This algorithm finds the equivalent prefix expression P of an infix expression Q.

    1. Push ( onto STACK and add ) to the end of Q.

    2. Scan Q from right to left and repeat Steps 3 and 6 for each element of Q until the STACK is

    empty.

    3. If an operand is encountered, add it to P.

    4. If an right parenthesis encountered, push it onto STACK.

    5. If an operator is encountered then :

    (a) Repeatedly pop from STACK and add to P each operator (on the top of STACK)

    which has the same precedence as or higher precedence than .

    (b) Add to STACK.

    [ End of If structure. ]

    6. If a left parenthesis is encountered then :

    (c) Repeatedly pop from STACK and add to P each operator (on the top of STACK)

    until a right parenthesis in encountered.

    (d) Remove the right parenthesis. [Do not add right parenthesis to P.]

    [ End of If structure. ]

    [ End of Step 2 loop. ]

    7. Reverse P.

    8. Exit.

    CODE: #include

    #include

    using namespace std;

    #define MAX 20

    class convert

    {

    char stack[MAX];

    int top;

    public:

    char pop();

    void push(char);

  • 38

    int prcd(char);

    int isoperator(char);

    void convertip(char *,char *);

    int parancheck(char *);

    convert()

    {

    top = -1;

    }

    };

    void convert::push(char item) {

    if(top == (MAX-1))

    cout

  • 39

    case ')':

    return 1;

    default:

    return 0;

    }

    }

    void convert::convertip(char *infix,char *prefix)

    {

    int i,symbol,j=0;

    char temp[40]={'\0'};

    for(i=0;i

  • 40

    prefix=strrev(prefix);

    }

    int convert::parancheck(char *exp) /* Ckheck whether fully paranthesised */

    {

    char temp;

    int i,valid=1,l;

    l=strlen(exp);

    for(i=0;i

  • 41

    OUTPUT: TRANSFORMATION OF INFIX TO PREFIX

    Enter A Valid Expression : 9 - 8 * ( 4 + 8 ) / 2 ^ 2

    The Equivalent Prefix Expression is : ^ / * - 9 8 + 4 8 2 2

    Press any key to continue

    DISCUSSION: 1. Here we have implemented the program to transform an infix expression to its equivalent

    prefix expression as well as to check whether the infix expression is properly parenthesized.

    4. For the parenthesis checker we have considered only the standard parenthesis (). For an

    input expression, it verifies that for each left parenthesis, there is a corresponding closing

    symbol and the symbols are appropriately nested.

    5. For the infix to prefix approach the given expression may contain left and right parenthesis

    besides operators and operands.

    We have assumed that the expression contains only the operators +,-,*,/ and ^, and the operands are

    given as integers.

  • 42

    8 IMPLEMENTATION AND BASIC

    OPERATIONS ON DOUBLY LINKED LIST

    OBJECTIVE: This program creates a doubly linked list and performs the following basic operations on it:

    1. Creating and deleting a list.

    2. Insertion : At beginning, At a given location, At end.

    3. Deletion: From beginning, From a given location, From End.

    4. Display its forward and backward traversal and sorting.

    5. Searching a given node and Count the total no. of nodes.

    ALGORITHM: ALGORITHM FOR CREATING A LIST:

    CREATELIST (START, END, DATA, NEXT, PREV )

    This algorithm creates a doubly linked list with root node START and tail node END. Each node has

    a data part, a PREV pointer to previous node and a NEXT pointer to next node. Here ITEM is an

    integer value to be assigned to a node.

    1. Create a new node NEWNODE.

    2. Set NEWNODE[ DATA ] = ITEM.

    NEWNODE[ NEXT ] = NEWNODE[ PREV ] = NULL.

    3. Set START= NEWNODE.

    4. If more nodes to be inserted, then:

    Call CREATELIST(START[ NEXT ], END, DATA, NEXT, PREV ).

    Else: END = NEWNODE.

    5. Exit.

    ALGORITHM FOR INSERTING AN ELEMENT AT THE BEGINNING OF THE LIST:

    INSERTBEG (START,END, DATA, NEXT, PREV )

    This algorithm inserts ITEM as the first node in the list.

    1. Create a new node PTR.

    2. Set PTR[ DATA ] = ITEM. [ Copies new data into new node. ]

    PTR[ NEXT ] = PTR[ PREV ] = NULL.

    3. Set PTR[ NEXT ] = START and START[ PREV ] = PTR. [ Add before START. ]

    4. Set START = PTR. [ Changes START so that it points to the new node. ]

    5. Exit.

    ALGORITHM FOR INSERTION AT A GIVEN LOCATION:

    INSERTLOC ( START, END, DATA, NEXT, PREV, ITEM, LOC )

    This algorithm inserts ITEM at LOC position.

    1. [ Initialize location counter. ] Set POS = 0.

    2. Set TEMP = START.

    3. If LOC = 0, then: Call INSERTBEG( START, END, DATA,NEXT, PREV,ITEM) and Exit.

    4. Repeat while TEMP NULL and POS LOC: [Search for LOC. ]

  • 43

    a. Set PRE = TEMP and TEMP = TEMP[ NEXT ].

    b. Set POS = POS + 1 [ Increase counter. ]

    [ End of while loop. ]

    5. If POS LOC, then: Write: LOC NOT FOUND.

    Else:Create a new node PTR.

    a. Set PTR[ DATA ] = ITEM. [ Copies new data into new node. ]

    PTR[ NEXT ] = PTR[ PREV ] = NULL.

    b. PTR[ NEXT ]=TEMP and TEMP[ PREV ] = PTR.

    c. Set PRE[ NEXT ] = PTR and PTR[ PREV ] = PRE. [ Insert new data at required

    location. ]

    [ End of If structure. ] 6. Exit.

    ALGORITHM FOR INSERTING AN ELEMENT AT THE END OF THE LIST:

    INSERTEND ( START, END, DATA, NEXT, PREV, ITEM )

    This algorithm inserts ITEM as the last node in the list.

    1. Create a new node PTR and Set PTR[ DATA ] = ITEM. [ Copies new data into new node.]

    2. Set PTR[ NEXT ] = PTR[ PREV ] = NULL.

    3. Set PTR[ PREV ] = END and END[ NEXT ] = PTR. [ Insert PTR as the last node. ]

    4. END = PTR. [ Make PTR the tail node. ]

    5. Exit.

    ALGORITHM TO DISPLAY A LIST:

    DISPLAY ( START, DATA, NEXT, PREV ) This algorithm displays the nodes of the list.

    1. Set TEMP = START.

    2. Repeat while TEMP NULL: [ Forward Traversing. ]

    Write: TEMP[ DATA ].

    Set TEMP = TEMP[ NEXT ]. [ Traverse next node. ]

    [ End of while loop. ]

    3. Set TEMP = END.

    4. Repeat while TEMP NULL: [ Backward Traversing. ]

    Write: TEMP[ DATA ].

    Set TEMP = TEMP[ PREV ]. [ Traverse next node. ]

    [ End of while loop. ]

    5. Exit.

    ALGORITHM FOR DELETING AN ELEMENT FROM THE BEGINNING OF THE LIST:

    DELETEBEG ( START, END, DATA, NEXT, PREV )

    This algorithm deletes the first node of the list.

    1. Set PTR = START. [ Copies new data into new node. ]

    2. Set START = START[ NEXT ] and START[ PREV ] = NULL.

    3. Set ITEM = PTR[ DATA ].

    4. FREE PTR.

    5. Exit.

    ALGORITHM FOR DELETING AN ELEMENT FROM A GIVEN LOCATION:

    DELETELOC ( START, DATA, NEXT, PREV, LOC )

    This algorithm deletes the node from LOC position.

    1. [ Initialize location counter ] Set POS = 0.

    2. Set TEMP = START.

    3. If LOC = 0, then: Call DELETEBEG( START, END, DATA,NEXT, PREV ) and Exit.

    4. Repeat while TEMP[ NEXT ] NULL and POS LOC: [Search for LOC. ]

  • 44

    a. Set PRE = TEMP and TEMP = TEMP[ NEXT ].

    b. Set POS = POS + 1. [ Increase counter. ]

    [ End of while loop. ]

    5. If POS LOC, then: Write: LOC NOT FOUND.

    Else:

    a. Set PRE[ NEXT ] = TEMP[ NEXT ]. [ Copies new data into new node. ]

    b. Set TEMP = TEMP[ NEXT ] and TEMP[ PREV ] = PRE.

    [ End of If structure. ] 6. Exit.

    ALGORITHM FOR DELETING AN ELEMENT FROM THE END OF THE LIST:

    DELETEEND ( START, DATA, NEXT, PREV, ITEM )

    This algorithm deletes the last node of the list.

    1. If START[ NEXT ] = NULL, then: Return = START[ DATA ].

    Set START = END = NULL.

    Else:

    a. Set TEMP = END.

    b. Set END = END[ PREV ] and END[ NEXT ] = NULL.

    c. FREE TEMP. [ Remove TEMP from memory. ]

    [ End of If structure. ]

    2. Exit.

    ALGORITHM FOR COUNTING TOTAL NO. OF NODES PRESENT IN THE LIST:

    COUNTNODES(START,NEXT) This algorithm counts and returns the total no. of nodes present in the list. Here COUNT is an integer variable used to count the nodes.

    1. Set TEMP = START and COUNT = 0. [ Initialize counter. ]

    2. Repeat while TEMP[ NEXT ] NULL:

    Set COUNT = COUNT + 1. [ Increase counter. ]

    Set TEMP = TEMP[ NEXT ]. [ Move to the next node. ]

    [ End of while loop. ]

    3. Return COUNT.

    4. Exit.

    ALGORITHM FOR SEARCHING AN ELEMENT FROM THE LIST:

    SEARCH( START,DATA, NEXT, PREV, INFO )

    This algorithm searches the node having the given value INFO and returns the location LOC.

    1. Set LOC = 0. [ Initialize counter. ]

    2. Set TEMP = START.

    3. Repeat while TEMP NULL and TEMP[ DATA ] INFO: [ Search for node with value

    INFO. ]

    Set LOC = LOC + 1. [ Increase counter. ]

    Set TEMP = TEMP[ NEXT ]. [ Move to the next node. ]

    [ End of while loop. ]

    4. If TEMP = NULL, then: Write: NODE NOT FOUND.

    Else: Return LOC.

    [ End of If structure. ]

    5. Exit.

    ALGORITHM FOR SORTING THE LIST IN ASCENDING ORDER:

    SORT( START, DATA, NEXT, PREV ) This algorithm sorts the list in ascending order using bubble sort.

    1. Set PASS = START. 2. Repeat Step 4 to 6 while PASS[ NEXT ] NULL.

  • 45

    3. Set SAVE = PASS[ NEXT ]. 4. Repeat Step a to d while SAVE NULL:

    a. If PASS[ DATA ] > SAVE[ DATA ], then: [ Exchange values of nodes. ] Set TEMP = PASS[ DATA ]. [ Temp is temporary integer variable. ] Set PASS[ DATA ] = SAVE[ DATA ]. Set SAVE[ DATA ] = TEMP. [ End of If structure. ]

    b. Set SAVE = SAVE[ NEXT ]. [ End of Step 4 loop. ]

    5. Set PASS = PASS[ NEXT ]. [ End of Step 2 loop. ]

    6. Exit.

    CODE: #include

    #include

    #include

    #include

    typedef class node

    {

    public:

    int data;

    class node *next;

    class node *prev;

    }node;

    int size=sizeof(node);

    class list

    {

    node *root,*end;

    friend void access();

    static int k;

    public:

    void createlist(node **, node **);

    void display(node *,node *);

    void insert(node **,node **,int);

    void deletenode(node **,node **);

    void sort(node **,node **);

    int search(node *,int);

    int count_nodes(node *,node *);

    void deletelist(node **,node **);

    list() { /* Default constructor definition */

    root=end=NULL;

    }

    };

    int list::k; /* Initialize static variable */

    void list::createlist(node **head, node **tail)

    {

    k++;

    node *ptr,*newn;

    char chk;

    do{

    newn=(node*)malloc(size); /* Create a new node */

    cout

  • 46

    cin>>newn->data;

    newn->next=NULL;

    newn->prev=NULL;

    if(*head==NULL)

    *head=newn;

    else

    {

    ptr->next=newn;

    newn->prev=ptr;

    }

    ptr=newn;

    coutchk;

    }while(chk=='y'||chk=='Y');

    *tail=newn;

    }

    void list::display(node *head, node *tail)

    {

    node *temp;

    temp=head;

    cout

  • 47

    case 2:

    coutnext=temp; /* Insert at given location */

    temp->prev=ptr;

    pre->next=ptr;

    ptr->prev=pre;

    flag=1;

    }

    }

    }

    break;

    case 3:

    ptr->prev=*tail;

    (*tail)->next=ptr;

    flag=1;

    *tail=ptr;

    break;

    default:

    cout

  • 48

    coutprev=NULL;

    item=pre->data;

    free(pre);

    flag=1;

    break;

    case 2:

    coutinfo;

    temp=*head;

    if(info==1) { /* Delete 1st node */

    pre=*head;

    *head=(*head)->next; /* Set the 2nd node as head */

    (*head)->prev=NULL;

    item=pre->data;

    free(pre);

    flag=1;

    }

    else {

    while((temp->next!=NULL)&&(loc!=info)) { /* Find the location */

    pre=temp;

    temp=temp->next;

    loc++;

    }

    if(loc!=info)

    coutnext==NULL){

    pre->next=NULL;

    *tail=pre;

    }

    else {

    pre->next=temp->next; /* Delete given location */

    temp=temp->next;

    temp->prev=pre;

    }

    flag=1;

    }

    }

    break;

    case 3:

    if((*head)->next==NULL){

    item=(*head)->data;

  • 49

    *head=NULL;

    *tail=NULL;

    flag=1;

    }

    else{

    pre=*tail;

    *tail=(*tail)->prev; /* Set the 2nd node as head */

    (*tail)->next=NULL;

    item=pre->data;

    free(pre);

    flag=1;

    }

    break;

    default:

    coutdata;

    curr->data=save->data;

    save->data=temp;

    }

    }

    }

    }

    int list::search(node *head,int item)

    {

    node *temp;

    int loc=1;

    temp=head;

    while((temp!=NULL)&&(temp->data!=item)) { /* Search for element */

    temp=temp->next;

    loc++; /* Store location */

    }

    if(temp==NULL) /* Search unsuccessful */

    return(-1);

    else /* item found */

    return(loc); /* Return location of item */

    }

    int list::count_nodes(node *head,node *tail)

    {

    int count=0;

    node *curr;

  • 50

    for(curr=head;curr!=NULL;curr=curr->next)

    count++; /* Increase counter */

    return(count);

    }

    void list::deletelist(node **head,node **tail)

    {

    node *ptr;

    while(*head!=NULL){

    ptr=*head;

    *head=(*head)->next;

    free(ptr);

    }

    k=0;

    }

    void access()

    {

    list l;

    char ck;

    int ch,val,count=0,loc;

    while(1){

    /* Display Menu */

    cout

  • 51

    if(ck=='Y'||ck=='y')

    l.createlist(&l.root,&l.end); /* create a new list */

    else

    break;

    }

    else /* insert a value in list */

    {

    coutval;

    l.insert(&l.root,&l.end,val);

    l.display(l.root,l.end); /* call display function */

    }

    break;

    case 4:

    if(l.k==0)

    cout

  • 52

    {

    coutval;

    loc=l.search(l.root,val);

    if(loc==-1)

    cout

  • 53

    OUTPUT: ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 1

    Enter Value : 3

    Want to add another node [Y/N] : y

    Enter Value : 7

    Want to add another node [Y/N] : n

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 2

    Forward Travarsal : root -> 3 -> 7 -> end

    Backward Travarsal : end -> 7 -> 3 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 3

    Enter Value to be inserted : 8

    +++++++++OPTIONS FOR INSERTION+++++++++

    1. Insert at beginning.

    2. Insert at given location.

    3. Insert at end.

  • 54

    Select where you want to insert...1

    8 has been inserted in list

    Forward Travarsal : root -> 8 -> 3 -> 7 -> end

    Backward Travarsal : end -> 7 -> 3 -> 8 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 3

    Enter Value to be inserted : 9

    +++++++++OPTIONS FOR INSERTION+++++++++

    1. Insert at beginning.

    2. Insert at given location.

    3. Insert at end.

    Select where you want to insert...3

    9 has been inserted in list

    Forward Travarsal : root -> 8 -> 3 -> 7 -> 9 -> end

    Backward Travarsal : end -> 9 -> 7 -> 3 -> 8 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 3

    Enter Value to be inserted : 7

    +++++++++OPTIONS FOR INSERTION+++++++++

    1. Insert at beginning.

    2. Insert at given location.

    3. Insert at end.

    Select where you want to insert...2

    Enter location where 7 to be inserted : 2

    7 has been inserted in list

  • 55

    Forward Travarsal : root -> 8 -> 7 -> 3 -> 7 -> 9 -> end

    Backward Travarsal : end -> 9 -> 7 -> 3 -> 7 -> 8 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 5

    Forward Travarsal : root -> 3 -> 7 -> 7 -> 8 -> 9 -> end

    Backward Travarsal : end -> 9 -> 8 -> 7 -> 7 -> 3 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 7

    Total no. of nodes = 5

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 6

    Enter value of node to be searched : 8

    Location of 8 is 4

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

  • 56

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 6

    Enter value of node to be searched : 1

    1 is not in list.

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 4

    +++++++++OPTIONS FOR DELETION+++++++++

    1. Delete from beginning.

    2. Delete from given location.

    3. Delete from end.

    Select from where you want to delete...1

    3 has been deleted from list

    Forward Travarsal : root -> 7 -> 7 -> 8 -> 9 -> end

    Backward Travarsal : end -> 9 -> 8 -> 7 -> 7 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 4

    +++++++++OPTIONS FOR DELETION+++++++++

    1. Delete from beginning.

    2. Delete from given location.

    3. Delete from end.

    Select from where you want to delete...3

    9 has been deleted from list

    Forward Travarsal : root -> 7 -> 7 -> 8 -> end

    Backward Travarsal : end -> 8 -> 7 -> 7 -> root

  • 57

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 4

    +++++++++OPTIONS FOR DELETION+++++++++

    1. Delete from beginning.

    2. Delete from given location.

    3. Delete from end.

    Select from where you want to delete...2

    Enter location from where to delete: 8

    Location not found.List has fewer nodes

    Forward Travarsal : root -> 7 -> 7 -> 8 -> end

    Backward Travarsal : end -> 8 -> 7 -> 7 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 4

    +++++++++OPTIONS FOR DELETION+++++++++

    1. Delete from beginning.

    2. Delete from given location.

    3. Delete from end.

    Select from where you want to delete...2

    Enter location from where to delete: 2

    7 has been deleted from list

    Forward Travarsal : root -> 7 -> 8 -> end

    Backward Travarsal : end -> 8 -> 7 -> root

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

  • 58

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 1

    A list is already exists.Want to replace it?[Y/N] : n

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 8

    All data you inserted is being removed from memory. Do you agree?[Y/N] : y

    List has been deleted.

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 2

    Create a list first

    ++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++

    1. Create List.

    2. Display.

    3. Insert.

    4. Delete.

    5. Sort list.

    6. Search an element.

    7. Count total no. of nodes.

    8. Remove list.

    9. Exit.

    Enter your choice : 9

    +++++++++THANK YOU+++++++++

    Press any key to continue

  • 59

    DISCUSSION: 1. Every node of a doubly linked list contains an information part which contains the integer

    value held by the node and two address part which points to the previous and next nodes. 2. The normal and reverse both traversal of the list have been displayed. Insertion (or deletion)

    of a node can be made at (or from) any position of a list. 3. To sort the list Bubble Sort technique has been applied. 4. To search an element from the list linear search has been used.

  • 60

    9 EVALUATION OF POSTFIX EXPRESSION

    OBJECTIVE: We have implemented a C++ program to transform an infix expression into its equivalent postfix

    expression and then toevaluate the postfix equation.

    ALGORITHM: INFIXTOPOSTFIX ( Q, P, STACK )

    This algorithm finds the equivalent postfix expression P of an infix expression Q.

    1. Push ( onto STACK and add ) to the end of Q.

    2. Scan Q from left to right and repeat Steps 3 and 6 for each element of Q until the STACK is

    empty.

    3. If an operand is encountered, add it to P.

    4. If an left parenthesis encountered, push it onto STACK.

    5. If an operator is encountered then :

    (e) Repeatedly pop from STACK and add to P each operator (on the top of STACK)

    which has the same precedence as or higher precedence than .

    (f) Add to STACK.

    [ End of If structure. ]

    6. If a right parenthesis is encountered then :

    (g) Repeatedly pop from STACK and add to P each operator (on the top of STACK)

    until a left parenthesis in encountered.

    (h) Remove the left parenthesis. [Do not add left parenthesis to P.]

    [ End of If structure. ]

    [ End of Step 2 loop. ]

    7. Exit.

    POSTFIXEVAL ( VALUE, STACK, P )

    This algorithm finds the VALUE of an arithmetic expression P written in postfix notation.

    1. Add anycharacter # at the end of P. [ This acts as sentinel. ]

    2. Scan P from left to right and repeat Steps 3 and 4 for each element of P until the sentinel #

    is encountered.

    3. If an operand is encountered, put it on STACK.

    4. If an operator is encountered then :

    (i) Remove the two top elements of STACK, where A is the top element as B is the

    next-to-top element.

    (j) Evaluate B A.

    (k) Place the result of (b) back on STACK.

    [ End of If structure. ]

    [ End of Step 2 loop. ]

    5. Set VALUE equal to top element of STACK.

    6. Exit.

  • 61

    CODE: #include

    #include

    #include

    using namespace std;

    #define MAX 40

    class convert

    {

    char stack[MAX];

    double post[MAX];

    int top;

    public:

    char pop();

    void push(char);

    int prcd(char);

    int isoperator(char);

    void convertip(char *,char *);

    int parancheck(char *);

    convert()

    {

    top = -1;

    }

    };

    class eval

    {

    double post[MAX];

    int top;

    public:

    double pop();

    void push(double);

    double evalute(char *);

    double calc(double,double,char);

    eval()

    {

    top = -1;

    }

    };

    void convert::push(char item)

    {

    if(top == (MAX-1))

    cout

  • 62

    } /* End of pop() */

    void eval::push(double item)

    {

    if(top == (MAX-1))

    cout

  • 63

    switch(c)

    {

    case '+':

    return(a+b);

    case '-':

    return(a-b);

    case '*':

    return(a*b);

    case '/':

    return(a/b);

    case '^':

    return(pow(a,b));

    }

    return(0);

    }

    double eval::evalute(char *exp)

    {

    convert k;

    float op1,op2,value;

    char op[5]={'\0'};

    while(*exp)

    {

    if(isdigit(*exp)||*exp=='.') /* if a digit or a decimal found */

    {

    int i=0;

    while(*exp!=' ') /* retrive the full number */

    {

    op[i++]=*exp;

    exp++;

    }

    op[i]='\0';

    double c=atof(op);/* convert the number from character to type double */

    push(c);

    }

    else if(k.isoperator(*exp)) /* if an operator found */

    { /* perform calculation */

    op2=pop();

    op1=pop();

    value=calc(op1,op2,*exp);

    push(value); /* save the intermediate value in stack */

    }

    exp++;

    }

    return(pop());

    }

    void convert::convertip(char *infix,char *postfix)

    {

    int i,symbol,j=0;

    char temp[MAX]={'\0'};

    for(i=0;i

  • 64

    if(isoperator(infix[i+1])==1)

    temp[j++]=' ';

    }

    temp[j]='\0';

    strcpy(infix,temp);

    j=0;

    stack[++top]='#';

    for(i=0;i

  • 65

    int i,valid=1,l;

    l=strlen(exp);

    for(i=0;i

  • 66

    OUTPUT: TRANSFORMATION OF INFIX TO POSTFIX

    AND EVALUATION OF THE POSTFIX EQUATION

    Enter A Valid Expression : 0 . 5* ( (19 -2 . 5 ) +4 )/2 ^2

    The Equivalent postfix Expression is : 0.5 19 2.5 - 4 + * 2 2 ^ /

    Result = 2.5625

    Press any key to continue

    DISCUSSION: 1. Here we have implemented the program to transform an infix expression to its equivalent

    postfix expression as well as to evaluate the postfix expression. 2. For the infix to postfix approach the given expression may contain left and right parenthesis

    besides operators and operands. 3. We have assumed that the expression contains only the operators +,-,*,/ and ^, and the

    operands are given as integers.

  • 67

    10 BINARY SEARCH TREE

    OBJECTIVE: This program creates a binary search tree performs the following operations on it:

    1. Insert an element.

    2. Delete an element.

    3. Traverse in preorder.

    4. Traverse in inorder.

    5. Traverse in postorder.

    ALGORITHM: ALGORITHM FOR INSERTING AN ELEMENT IN THE TREE:

    INSERT ( ROOT, DATA, LEFT, RIGHT, ITEM )

    This algorithm inserts ITEM in the tree.

    1. If ROOT = NULL, then:

    (a) Create a new binary search tree.

    (b) Insert ITEM as root.

    (c) Set ROOT[ LEFT ] = NULL and ROOT[ RIGHT ] = NULL.

    Else:

    (a) If ITEM ROOT[ DATA ], then: Insert ITEM in right sub-tree.

    (c) Else Write: Duplicate Data.

    [End of If structure.]

    [End of If structure.]

    2. Exit. ALGORITHM FOR DELETING AN ELEMENT FROM THE TREE:

    DELETE( ROOT, DATA, LEFT, RIGHT, ITEM )

    This algorithm deletes ITEM in the tree T.

    1. If ROOT = NULL, then :

    Write : ITEM not in tree.

    Return.

    Else PAR = ROOT.

    [ End of If Structure. ]

    2. If ITEM DATA, then :

    Call DELETE ( PAR, DATA, LEFT, RIGHT, ITEM ).

    4. Else If PAR has left and right child, then :

    Replace PAR with largest node in left child.

    5. Else

    (a) If PAR is terminal node, then :

  • 68

    Set PAR = NULL.

    (b) Else if PAR has only left child, then :

    Replace PAR with left node.

    (c) ElseReplace PAR with right node.

    [ End of If Structure. ]

    [ End of If Structure. ]

    ALGORITHM FOR PREORDER TRAVERSAL:

    PREORDER ( ROOT, LEFT, RIGHT )

    This algorithm traverses the tree in preorder.

    1. Visit the root node.

    2. Traverse the left sub-tree in preorder.

    3. Traverse the right sub-tree in preorder.

    ALGORITHM FOR INORDER TRAVERSAL:

    INORDER ( ROOT, LEFT, RIGHT )

    This algorithm traverses the tree in inorder.

    1. Traverse the left sub-tree in inorder.

    2. Visit the root node.

    3. Traverse the right sub-tree in inorder.

    ALGORITHM FOR POSTORDER TRAVERSAL:

    INORDER ( ROOT, LEFT, RIGHT )

    This algorithm traverses the tree in postorder.

    1. Traverse the left sub-tree in postorder.

    2. Traverse the right sub-tree in postorder.

    3. Visit the root node.

    CODE: #include

    #include

    typedef class node{

    public:

    int info;

    class node *left,*right;

    } BST; /* define tree structure */

    class tree{

    BST *root;

    friend void access();

    public:

    BST *getnode();

    void insert();

    void del(BST **,int);

    BST *findlargest(BST *);

    voidinorder(BST *);

    void preorder(BST *);

    voidpostorder(BST *);

    tree() {

    root='\0';

    }

    };

    BST *tree::getnode() {

  • 69

    BST *p;

    p=new BST; /* create node */

    return(p);

    }

    void tree::insert() {

    int data;

    BST *ptr,*prev,*p;

    coutdata; /* take input of data of the child node */

    ptr=root;

    while(ptr!='\0'&&ptr->info!=data) {

    if(ptr->inforight;

    }

    else {

    prev=ptr;

    ptr=ptr->left;

    }

    }

    if(ptr!='\0')

    coutleft=p->right='\0';

    if(prev->info

  • 70

    (*tree)->info=ptr->info;

    del(&((*tree)->left),ptr->info);

    }

    else {

    ptr=*tree;

    /* terminal node */

    if(((*tree)->left==NULL)&&((*tree)->right==NULL))

    *tree=NULL;

    else if((*tree)->left!=NULL) /* Left child only */

    *tree=(*tree)->left;

    else /* Right child only */

    *tree=(*tree)->right;

    free(ptr);

    }

    }

    void tree::inorder(BST *p) {

    if(p!='\0')

    {

    inorder(p->left);

    cout

  • 71

    switch(ch) {

    case 1:

    t.insert(); /* call the function insert() to insert data in node */

    break;

    case 2:

    coutele;

    t.del(&t.root,ele);

    break;

    case 3:

    cout

  • 72

    Enter value : 32

    Inserted at RIGHT of 25

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 1

    Enter value : 15

    Inserted at LEFT of 25

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 1

    Enter value : 68

    Inserted at RIGHT of 32

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 1

    Enter value : 28

    Inserted at LEFT of 32

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 1

  • 73

    Enter value : 18

    Inserted at RIGHT of 15

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 1

    Enter value : 11

    Inserted at LEFT of 15

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 3

    Preorder Traversal :

    25 15 11 18 32 28 68

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 4

    InorderTraversal :

    11 15 18 25 28 32 68

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 5

    PostorderTraversal :

    11 18 15 28 68 32 25

  • 74

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 2

    Enter value : 32

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 3

    Preorder Traversal :

    25 15 11 18 28 68

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 4

    InorderTraversal :

    11 15 18 25 28 68

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 5

    PostorderTraversal :

    11 18 15 68 28 25

    1. Insert

    2. Delete a node.

    3. Preorder Traversing.

    4. Inorder Traversing

  • 75

    5. Postorder Traversing.

    6. Exit.

    Enter your choice : 6

    Press any key to continue

    DISCUSSION: 1. The root of this tree is the biggest one.

    2. The value of key in left sub-tree is always smaller than root and the value of key in right sub-

    tree is always larger than root. All sub-trees of the left & right children observe these two

    rules.

    3. By inorder traversal of this tree, we get the elements in sorted order.

    4. While deleting a node from the tree we can replace the node with the largest element of its

    left sub tree or the smallest element of its right sub tree. Here we have used largest of left sub

    tree.