Concept of Data Structure
 Data Structure:

A means of storing a collection of data.
                          OR
It is the specification of the elements of the
   structure, the relationships between them, and
   the operation that may be performed upon them.



 04/09/13                            1
Computer Science & Data
                 Structure
  Computer science is concern with study of
  Methods for effectively using a computer to
  solve problems.
                  or
In determining exactly the problem to be solved.
This process entails:
1. Gaining an understanding of the problem.

2. Translating vague descriptions, goals, and contradictory
   requests, and often unstated desires, into a precisely
   formulated conceptual Solution


04/09/13                                      2
Computer Science & Data Structure
           (Continue)
3.   Implementing the solution with a computer
     program. This solution typically consists of
     two parts: algorithms and data structures:
Algorithm:
An algorithm is a concise specification of a method
 for solving a problem.
Data Structure:
A data structure can be viewed as consisting of a set
of algorithms for performing operations on the data
 it stores.

04/09/13                                   3
Computer Science & Data Structure
           (Continue)
Data Structure & Algorithm
Algorithms are part of what constitutes
a data structure. In constructing a solution to
a problem, a data structure must be chosen
that allows the data to be operated upon
easily in the manner required by the
algorithm.

04/09/13                               4
   12
   Data Structures vs. Algorithms

   •Choice of data structures
   �A primary design consideration at many times
   �Determines the algorithms to be used
   �“A well-designed data structure allows a variety of critical operations to be
    performed using as few resources, both execution time and memory space, as
    possible.”
   •The opposite direction sometimes
   �Certain algorithms require particular data structures
   �E.g., shortest path algorithm needs priority queues


     –   Data Structures
     –   How do we organize
     –   the data to be
     –   handled?

              Algorithms
              Describe the process
              by which data is
              handled.Duality



04/09/13                                                           5
04/09/13   6
Abstract Data Types(ADT)
What is Abstraction?
To abstract is to ignore some details
of a thing in favor of others.

ADT & Data structure
An Abstract Data Type (ADT) is more a way of
 looking at a data structure: focusing on what it
 does and ignoring how it does its job.
04/09/13                                7
Abstract Data Types(ADT)
 Why need      Abstraction?
   Abstraction is important in problem solving because
   it allows problem solvers to focus on essential details
   while ignoring the inessential, thus simplifying the
   problem and bringing to attention those aspects of the
   problem involved in its solution. Once an abstract
   data type is understood and documented, it serves as a
   specification that programmers can use to guide their
   choice of data representation and operation
   implementation, and as a standard for ensuring
   program correctness.
04/09/13                                    8
Abstract Data Types(ADT)
Abstract data types:
Each data structure can be developed around the
concept of an abstract data type that defines both data
organization and data handling operations.
 A mathematical entity consisting of a set of values
  and a collection of operations that manipulate them.
  For example, the Integer abstract data type consists of
  a carrier set containing the positive and negative
  whole numbers and 0, and a collection of operations
  manipulating these values, such as addition,
  subtraction, multiplication, equality comparison, and
  order comparison.

04/09/13                                   9
Abstract Data Types(ADT)
 Abstract data types are important in computer science
  because they provide a clear and precise way to
  specify what data a program must manipulate, and
  how the program must manipulate its data, without
  regard to details about how data are represented or
  how operations are implemented.
 ADT defines both data organization and data
  handling operations.
 The study of data structure is organized around a
  collection of abstract data types that includes lists,
  trees, sets, graphs, and dictionaries.

04/09/13                                  10
Abstract Data Types(ADT)
 ADT is not a part of a program ,since   a
  program written in a programming language
  requires the definition of data structure, not
  just the operations on the data structure.
 ADT is a useful tool for specifying the logical
  properties of a data type.
 ADT is not concerned with the time/space
  efficiency of data type.

04/09/13                             11
Specification of ADT
    ADT consist of 2 parts.
1.   Value Definition.
2.   Operator Definition.




04/09/13                       12
Specification of ADT
1.   Value Definition.
It defines the collection of values for the
ADT and consist of two parts.
a)    Definition Clause
b)    Condition Clause
 e.g. For ADT RATIONAL
Value definition: it states that RATIONAL value
consist of two integers ,the second of which does not equal
to zero.
The keyword abstract typedef introduce a value definition.


04/09/13                                         13
Specification of ADT
 Condition Clause
 Used to specify any conditions on the newly defined
  type.
 The keyword condition is used to specify any
  conditions on the newly defined type.
For e.g. for RATIONAL ADT
Condition Clause: denominator may not be zero.
Note :The definition clause is required but the
condition clause may not be necessary for every
ADT.

04/09/13                                 14
Specification of ADT
2.   Operator Definition.
    It defines the operations that are to be
     performed on a data set.
    Each operator is defined as an abstract
     function with three parts:
    Header.
    Optional preconditions .
    Post conditions.
04/09/13                               15
Specification of ADT
2.   Operator Definition.
For e.g. :Operator definition for RATIONAL ADT
includes the operations of creation ,addition ,
multiplication and equality.
    Now for multiplication operation the operator definition for
     RATIONAL ADT is.
    Abstract RATIONAL mult(a,b)……/*header*/
     RATIONAL a, b; ……….                /*header*/
     mul[0]=a[0]*b[0]; ………………….. /*postcond*/
     mul[1]=a[1]*b[1];……………………/postcond*/



04/09/13                                          16
Complete example of RATIONL
                ADT
 /* value definition*/
 Abstract typedef< int , int >RATIONAL;
 Condition RATIONAL[1]!=0;
 /* Operator definition */
 Abstract equal(a,b)
 RATIONAL a ,b;
 Postcondition equal==(a[0]*b[1]==b[0]*b[1]);
 Like this we can declare the other operations.


04/09/13                            17
Classification of Data Structure
Linear and Non-Linear:

    In linear data structure, the data items are arranged
     in linear sequence. e.g. Array, Stack, Queue, Linked
     List.

    In non-linear data items are not in sequence. e.g.
     Tree , graph ,Heap


04/09/13                                    18
Classification of Data Structure
               (Continue)
Homogenous and Non-homogenous.

     In homogenous data structure ,all the elements are
     of same type e.g. Array.
    In non-homogenous data structure, the elements
     may or may not be of same type e.g. Record.




04/09/13                                   19
Classification of Data Structure
               (Continue)
Primitive and Non-Primitive:
Primitive data structures constitute the
number and the characters which are built
programs. examples int. reals,pointer
data,charaters data, logical data.




04/09/13                            20
What is STACK or Pushdown
              List
A ordered collection of items
 into which new items may be
 inserted and from which items
 may be deleted at one end,
 called the top of stack.


04/09/13              21
Operations on STACK
 PUSH:When      item is added in stack
 POP:When item is removed from
  stack
 EMPTY:Stack containing no items.

 StackTop:Determine what the top
  item on a stack without removing
  it.this is a combination of push & pop


04/09/13                      22
Push & Pop in STACK
 PUSH Operation
 PUSH(STACK ,TOP,MAX,ITEM)
 STACK--Name given to Array.
 TOP----It contains the location of top
  elements.
 MAX---It is maximum size of STACK.
 ITEM--->Value that is to be store in stack
     if top = MAX then stackfull
     top = top+1
     stack(top) = item
  Return
04/09/13                          23
Push & Pop in STACK
POP Operation
POP(STACK ,TOP,ITEM)
if top = 0 then Underflow
    item = stack(top)
    top = top-1
   Return
04/09/13                   24
Applications of STACK
Expression Evaluation
Parenthesis Checker

Recursion




04/09/13                     25
Infix To Postfix Conversion of an
      Arithmetic Expression
Operator  preecedence
^ ---------Higher precedence

*,/--------Next Precedence.

+,_-------Least precedence.




04/09/13                26
Infix To Postfix Conversion of an
      Arithmetic Expression
    The rules to remember.
1.    Parenthesize the expression
      starting fro left to right.
2.    During Parenthesizing the
      expression the operands associated
      with operator having higher
     precedence are first parenthesized.

04/09/13                       27
Infix To Postfix Conversion of an
      Arithmetic Expression
3. The sub-expression which has been
   converted into postfix is to be
   treated as single operand.
4. Once the expression is converted to
   postfix form remove the
   parenthesis.
Example: A+B*C
 A+[(B+C)+(D+E)*F]/G
 Answer: ABC+DE+F*+G/+

04/09/13                     28
Algorithm for Conversing Infix
        Expression to Postfix Form
    Postfix(Q,P)
    Q—>Given Infix expression.
    P->Equivalent Postfix expression.
1.   Push “(“ onto STACK and add “)” to the
     end of Q.
2.   Scan Q from left to right and repeat step
     3 to 6 for each element of Q until the
     STACK is Empty.
3.   If an operand is encountered ,add it to P.
4.   If a left parenthesis is encountered ,push
     it onto STACK.
04/09/13                                 29
Algorithm for Conversing Infix
       Expression to Postfix Form
5. If an operator ® is encountered
   then:
(a) ADD ® to STACK
[End of IF]
(b) Repeatedly pop from STACK and
   add P each operator which has
   same precedence as or higher
   precedence than ®.

04/09/13                      30
Algorithm for Conversing Infix
       Expression to Postfix Form
6. If a right parenthesis is encountered
   then:
(a) Repeatedly pop from STACK and add to
   P each operator until a left parenthesis is
   encountered.
(b) Remove the left parenthesis. do not add
   it of P]
[End of If]
[End of step 2 loop]
7. Exit.


04/09/13                           31
Converting Infix Expression to
          Prefix Expression.
1.   Reverse the input string.
2.   Examine the next element in
     the input.
3.   If it is operand ,add it to the
     output string.
4.   If it is closing parenthesis ,
     push it on STACK.
04/09/13                      32
Converting Infix Expression to
          Prefix Expression.
5.   If it is operator , then:
     i) if STACK is empty, push –operation on
     STACK.
     ii) if the top of the stack is closing
     parenthesis push operator on STACK.
     iii) if it has same or higher priority then
     the top of STACK, push operator on S.
     iv) else pop the operator from the STACK
     and add it to output string, repeat S.

04/09/13                            33
Converting Infix Expression to
          Prefix Expression.
6.   If it is a opening parenthesis , pop
     operator from STACK and add them
     to S until a closing parenthesis is
     encountered. POP and discard the
     closing parenthesis.
7.   If there is more input go to step 2.
8.   If there is more input , unstack the
     remaining operators and add them.
9.   Reverse the output string.
04/09/13                       34
Algorithm to Evaluate a Postfix
              Expression
This algorithm finds the value of an
arithmetic expressions P written in
postfix notation. The algorithm uses a
STACK to hold operands , evaluate P.
1. Add right parenthesis “)” at the end
    of P.[This acts as sentinel]
2. Scan P from left to right and repeat
    step 3 & 4 for each element of P
    until the sentinel “)” is
    encountered.
04/09/13                     35
Algorithm to Evaluate a Postfix
              Expression
3.    If an operand is encountered , put it on
      STACK.
4. If an operator ® is encountered , then:
      A) Remove the two top elements of
      STACK, Where A is the top element and
      B is the next-to-top element.
      B)Evaluate B ®A.
      C)Place the result of (b) back o STACK.
      [End of IF]
      [End of step 2 loop]
6. Set value equal to the top element on
      STACK.
7. Exit.
04/09/13                              36
Parenthesis Checker
 Read exp
 Create empty Stack
 For each character C in exp
 If(current character is left symbol) then
 Push the character C onto Stack.
 Elseif(current character C is a right
  Symbol)then
 If(stack is empty)then
 Print:”Error:No matching open symbol”
 Exit


04/09/13                           37
Parenthesis Checker
 Else
 POP a symbol S from the Stack
 If (S doesnot correspond to C)then
 Print:”Error:Incorrect nesting of symbols”
 Exit
 Endif
 Endif
 Endif
 End for


04/09/13                          38
Parenthesis Checker
 If(stack is not empty)then
 Print:”Error:Missing closing
  symbols(s)”
 Else

 Print:”Input expression is ok”

 Endif

 End



04/09/13                      39
Example of STACK
   Many computer algorithms work best with stacks --- stacks are
    used for
   remembering partially completed tasks, and
   undoing (backtracking from) an action.
   An example of 1. is described in the next section, where sub
    expressions of an arithmetic expression are remembered for later
    computation. Another example is presented in the next lecture,
    where we see how the Java Virtual Machine uses a stack to
    remember all of a program's methods that have been called but
    are not yet finished.
   An example of 2. is the ``undo'' button on most text editors,
    which lets a person undo a typing error, or the ``back'' button on
    a web browser, which lets a user backtrack to a previous web
    page. Another example is a searching algorithm, which searches a
    maze and keeps a history of its moves in a stack. If the algorithm
    makes a false (bad) move, the move can be undone by retrieving
    the previous position from the stack.



04/09/13                                             40
STACK Implementation
   Static and dynamic data structures
   A stack can be stored in:
   • a static data structure
   OR
   • a dynamic data structure
   Static data structures
   These define collections of data which are fixed in size
    when the program is compiled.
   An array is a static data structure.
   Dynamic data structures
   These define collections of data which are variable in size
    and structure. They are
   created as the program executes, and grow and shrink to
    accommodate the data being
   stored.

04/09/13                                          41
TRANSPOSE OF SPARSE
                 MATRIX
   #include<stdio.h>
   #include<conio.h>
   // transpose for the sparse matrix
   void main()
   {
    //clrscr();
    int a[10][10],b[10][10];
    int m,n,p,q,t,col;
    int i,j;

   printf("enter the no of row and columns :n");
   scanf("%d %d",&m,&n);

04/09/13                                             42
TRANSPOSE OF SPARSE
                 MATRIX
   // assigning the value of matrix
    for(i=1;i<=m;i++)
    {
      for(j=1;j<=n;j++)
      {
        printf("a[%d][%d]= ",i,j);
        scanf("%d",&a[i][j]);
        }
     }




04/09/13                               43
TRANSPOSE OF SPARSE
                 MATRIX
   printf("nn");
   //displaying the matrix
    printf("nnThe matrix is :nn");
   for(i=1;i<=m;i++)
    {
      for(j=1;j<=n;j++)
      {
       printf("%d",a[i][j]);
        }
        printf("n");
      }


04/09/13                                  44
TRANSPOSE OF SPARSE
                 MATRIX
   t=0;
 printf("nnthe non zero value matrix are :nn");
 for(i=1;i<=m;i++)
 {
 for(j=1;j<=n;j++)
 {
// accepting only non zero value
 if(a[i][j]!=0)
 {




04/09/13                                          45
TRANSPOSE OF SPARSE
                 MATRIX
   t=t+1;
     b[t][1]=i;
     b[t][2]=j;
     b[t][3]=a[i][j];
      } }
   }
   b[0][0]=m;
   b[0][1]=n;
   b[0][2]=t;
   // displaying the matrix of non-zero value
   printf("n");
   For(i=0;i<=t;i++)
   printf(“%d “,a[i][0],a[i][1],a[i][2]);

04/09/13                                         46
TRANSPOSE OF SPARSE
              MATRIX
  // transpose of the matrix
 printf("nnthe transpose of the matrix :n ");
 if(t>0)
 {
 for(i=1;i<=n;i++)
 {
     for(j=1;j<=t;j++)
     {
      if(b[j][2]==i)
      {
        a[q][1]=b[j][2]; a[q][2]=b[j][1];
        a[q][3]=b[j][3]; q=q+1;
         } }
04/09/13 }
       }                                           47
TRANSPOSE OF SPARSE
                 MATRIX
   for(i=0;i<=t;i++)
   {
    printf("a[%d %d %d %dn",i,a[i][1],a[i][2],a[i][3]);
      }
    getch();
    }




04/09/13                                            48
Tower of Hanoi(An application of
      Recursion & Stack)
This problem is not specified in terms
  of recursion but the recursive
  technique can be used to produce a
  logical solution .
 Problem Definition:

 There are three pegs A,B,& C exist,
  any number of disks (n) of different
  diameters are placed on peg A so
  that a larger disk is always below a
  smaller disk.
04/09/13                      49
Tower of Hanoi(An application of
           Recursion & Stack)
 The  object is to move n disks to peg
  C ,using peg B as auxiliary.
 Only the top disk on any peg may be
  moved to any other peg, and a
  larger disk may never rest on a
  smaller one.

 Note:in    general it requires f(n)=2n-1
 moves
  04/09/13                     50
Recursive solution to tower of
          Hanoi problem
 To   move n disks from A to
   C using B as auxiliary:
1. If n==1 move the single disk
   from A to C and stop



04/09/13                  51
Recursive solution to tower of
            Hanoi problem
2.   Move the top n-1 disks from
     A to B , using C as auxiliary.
3.   Move the remaining disks
     from A to C
4.   Move the n-1 disks from B to
     C,using A as auxiliary.

04/09/13                    52
Recursive Implementation of Tower
            of Hanoi.
main()
{
int n;
scanf (“%d”, &n);
towers (n, ’A’, ’C’ ,’B’);
}
04/09/13                     53
towers(int n, char frompeg, char
  topeg,char auxpeg)
{
If (n==1)
{
printf (“n %s %c %s %c”, “move
  disk 1 from peg “,frompeg, “to
  peg”, topeg);
return;
}04/09/13              54
towers(n-1,frompeg,auxpeg,topeg)
printf (“n %s %d %s %c %s %c”,
  “move disk”, n, “from peg”, frompeg,
  “to peg”, topeg);
tower(n-1,auxpeg,topeg,frompeg);
}


  04/09/13                  55

Data structure

  • 1.
    Concept of DataStructure  Data Structure: A means of storing a collection of data. OR It is the specification of the elements of the structure, the relationships between them, and the operation that may be performed upon them. 04/09/13 1
  • 2.
    Computer Science &Data Structure Computer science is concern with study of Methods for effectively using a computer to solve problems. or In determining exactly the problem to be solved. This process entails: 1. Gaining an understanding of the problem. 2. Translating vague descriptions, goals, and contradictory requests, and often unstated desires, into a precisely formulated conceptual Solution 04/09/13 2
  • 3.
    Computer Science &Data Structure (Continue) 3. Implementing the solution with a computer program. This solution typically consists of two parts: algorithms and data structures: Algorithm: An algorithm is a concise specification of a method for solving a problem. Data Structure: A data structure can be viewed as consisting of a set of algorithms for performing operations on the data it stores. 04/09/13 3
  • 4.
    Computer Science &Data Structure (Continue) Data Structure & Algorithm Algorithms are part of what constitutes a data structure. In constructing a solution to a problem, a data structure must be chosen that allows the data to be operated upon easily in the manner required by the algorithm. 04/09/13 4
  • 5.
    12  Data Structures vs. Algorithms  •Choice of data structures  �A primary design consideration at many times  �Determines the algorithms to be used  �“A well-designed data structure allows a variety of critical operations to be performed using as few resources, both execution time and memory space, as possible.”  •The opposite direction sometimes  �Certain algorithms require particular data structures  �E.g., shortest path algorithm needs priority queues – Data Structures – How do we organize – the data to be – handled?  Algorithms  Describe the process  by which data is  handled.Duality 04/09/13 5
  • 6.
  • 7.
    Abstract Data Types(ADT) Whatis Abstraction? To abstract is to ignore some details of a thing in favor of others. ADT & Data structure An Abstract Data Type (ADT) is more a way of looking at a data structure: focusing on what it does and ignoring how it does its job. 04/09/13 7
  • 8.
    Abstract Data Types(ADT) Why need Abstraction? Abstraction is important in problem solving because it allows problem solvers to focus on essential details while ignoring the inessential, thus simplifying the problem and bringing to attention those aspects of the problem involved in its solution. Once an abstract data type is understood and documented, it serves as a specification that programmers can use to guide their choice of data representation and operation implementation, and as a standard for ensuring program correctness. 04/09/13 8
  • 9.
    Abstract Data Types(ADT) Abstractdata types: Each data structure can be developed around the concept of an abstract data type that defines both data organization and data handling operations.  A mathematical entity consisting of a set of values and a collection of operations that manipulate them. For example, the Integer abstract data type consists of a carrier set containing the positive and negative whole numbers and 0, and a collection of operations manipulating these values, such as addition, subtraction, multiplication, equality comparison, and order comparison. 04/09/13 9
  • 10.
    Abstract Data Types(ADT) Abstract data types are important in computer science because they provide a clear and precise way to specify what data a program must manipulate, and how the program must manipulate its data, without regard to details about how data are represented or how operations are implemented.  ADT defines both data organization and data handling operations.  The study of data structure is organized around a collection of abstract data types that includes lists, trees, sets, graphs, and dictionaries. 04/09/13 10
  • 11.
    Abstract Data Types(ADT) ADT is not a part of a program ,since a program written in a programming language requires the definition of data structure, not just the operations on the data structure.  ADT is a useful tool for specifying the logical properties of a data type.  ADT is not concerned with the time/space efficiency of data type. 04/09/13 11
  • 12.
    Specification of ADT  ADT consist of 2 parts. 1. Value Definition. 2. Operator Definition. 04/09/13 12
  • 13.
    Specification of ADT 1. Value Definition. It defines the collection of values for the ADT and consist of two parts. a) Definition Clause b) Condition Clause e.g. For ADT RATIONAL Value definition: it states that RATIONAL value consist of two integers ,the second of which does not equal to zero. The keyword abstract typedef introduce a value definition. 04/09/13 13
  • 14.
    Specification of ADT Condition Clause  Used to specify any conditions on the newly defined type.  The keyword condition is used to specify any conditions on the newly defined type. For e.g. for RATIONAL ADT Condition Clause: denominator may not be zero. Note :The definition clause is required but the condition clause may not be necessary for every ADT. 04/09/13 14
  • 15.
    Specification of ADT 2. Operator Definition.  It defines the operations that are to be performed on a data set.  Each operator is defined as an abstract function with three parts:  Header.  Optional preconditions .  Post conditions. 04/09/13 15
  • 16.
    Specification of ADT 2. Operator Definition. For e.g. :Operator definition for RATIONAL ADT includes the operations of creation ,addition , multiplication and equality.  Now for multiplication operation the operator definition for RATIONAL ADT is.  Abstract RATIONAL mult(a,b)……/*header*/ RATIONAL a, b; ………. /*header*/ mul[0]=a[0]*b[0]; ………………….. /*postcond*/ mul[1]=a[1]*b[1];……………………/postcond*/ 04/09/13 16
  • 17.
    Complete example ofRATIONL ADT  /* value definition*/  Abstract typedef< int , int >RATIONAL;  Condition RATIONAL[1]!=0;  /* Operator definition */  Abstract equal(a,b)  RATIONAL a ,b;  Postcondition equal==(a[0]*b[1]==b[0]*b[1]);  Like this we can declare the other operations. 04/09/13 17
  • 18.
    Classification of DataStructure Linear and Non-Linear:  In linear data structure, the data items are arranged in linear sequence. e.g. Array, Stack, Queue, Linked List.  In non-linear data items are not in sequence. e.g. Tree , graph ,Heap 04/09/13 18
  • 19.
    Classification of DataStructure (Continue) Homogenous and Non-homogenous.  In homogenous data structure ,all the elements are of same type e.g. Array.  In non-homogenous data structure, the elements may or may not be of same type e.g. Record. 04/09/13 19
  • 20.
    Classification of DataStructure (Continue) Primitive and Non-Primitive: Primitive data structures constitute the number and the characters which are built programs. examples int. reals,pointer data,charaters data, logical data. 04/09/13 20
  • 21.
    What is STACKor Pushdown List A ordered collection of items into which new items may be inserted and from which items may be deleted at one end, called the top of stack. 04/09/13 21
  • 22.
    Operations on STACK PUSH:When item is added in stack  POP:When item is removed from stack  EMPTY:Stack containing no items.  StackTop:Determine what the top item on a stack without removing it.this is a combination of push & pop 04/09/13 22
  • 23.
    Push & Popin STACK  PUSH Operation  PUSH(STACK ,TOP,MAX,ITEM)  STACK--Name given to Array.  TOP----It contains the location of top elements.  MAX---It is maximum size of STACK.  ITEM--->Value that is to be store in stack if top = MAX then stackfull top = top+1 stack(top) = item Return 04/09/13 23
  • 24.
    Push & Popin STACK POP Operation POP(STACK ,TOP,ITEM) if top = 0 then Underflow item = stack(top) top = top-1 Return 04/09/13 24
  • 25.
    Applications of STACK ExpressionEvaluation Parenthesis Checker Recursion 04/09/13 25
  • 26.
    Infix To PostfixConversion of an Arithmetic Expression Operator preecedence ^ ---------Higher precedence *,/--------Next Precedence. +,_-------Least precedence. 04/09/13 26
  • 27.
    Infix To PostfixConversion of an Arithmetic Expression  The rules to remember. 1. Parenthesize the expression starting fro left to right. 2. During Parenthesizing the expression the operands associated with operator having higher precedence are first parenthesized. 04/09/13 27
  • 28.
    Infix To PostfixConversion of an Arithmetic Expression 3. The sub-expression which has been converted into postfix is to be treated as single operand. 4. Once the expression is converted to postfix form remove the parenthesis. Example: A+B*C  A+[(B+C)+(D+E)*F]/G  Answer: ABC+DE+F*+G/+ 04/09/13 28
  • 29.
    Algorithm for ConversingInfix Expression to Postfix Form  Postfix(Q,P)  Q—>Given Infix expression.  P->Equivalent Postfix expression. 1. Push “(“ onto STACK and add “)” to the end of Q. 2. Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK is Empty. 3. If an operand is encountered ,add it to P. 4. If a left parenthesis is encountered ,push it onto STACK. 04/09/13 29
  • 30.
    Algorithm for ConversingInfix Expression to Postfix Form 5. If an operator ® is encountered then: (a) ADD ® to STACK [End of IF] (b) Repeatedly pop from STACK and add P each operator which has same precedence as or higher precedence than ®. 04/09/13 30
  • 31.
    Algorithm for ConversingInfix Expression to Postfix Form 6. If a right parenthesis is encountered then: (a) Repeatedly pop from STACK and add to P each operator until a left parenthesis is encountered. (b) Remove the left parenthesis. do not add it of P] [End of If] [End of step 2 loop] 7. Exit. 04/09/13 31
  • 32.
    Converting Infix Expressionto Prefix Expression. 1. Reverse the input string. 2. Examine the next element in the input. 3. If it is operand ,add it to the output string. 4. If it is closing parenthesis , push it on STACK. 04/09/13 32
  • 33.
    Converting Infix Expressionto Prefix Expression. 5. If it is operator , then: i) if STACK is empty, push –operation on STACK. ii) if the top of the stack is closing parenthesis push operator on STACK. iii) if it has same or higher priority then the top of STACK, push operator on S. iv) else pop the operator from the STACK and add it to output string, repeat S. 04/09/13 33
  • 34.
    Converting Infix Expressionto Prefix Expression. 6. If it is a opening parenthesis , pop operator from STACK and add them to S until a closing parenthesis is encountered. POP and discard the closing parenthesis. 7. If there is more input go to step 2. 8. If there is more input , unstack the remaining operators and add them. 9. Reverse the output string. 04/09/13 34
  • 35.
    Algorithm to Evaluatea Postfix Expression This algorithm finds the value of an arithmetic expressions P written in postfix notation. The algorithm uses a STACK to hold operands , evaluate P. 1. Add right parenthesis “)” at the end of P.[This acts as sentinel] 2. Scan P from left to right and repeat step 3 & 4 for each element of P until the sentinel “)” is encountered. 04/09/13 35
  • 36.
    Algorithm to Evaluatea Postfix Expression 3. If an operand is encountered , put it on STACK. 4. If an operator ® is encountered , then: A) Remove the two top elements of STACK, Where A is the top element and B is the next-to-top element. B)Evaluate B ®A. C)Place the result of (b) back o STACK. [End of IF] [End of step 2 loop] 6. Set value equal to the top element on STACK. 7. Exit. 04/09/13 36
  • 37.
    Parenthesis Checker  Readexp  Create empty Stack  For each character C in exp  If(current character is left symbol) then  Push the character C onto Stack.  Elseif(current character C is a right Symbol)then  If(stack is empty)then  Print:”Error:No matching open symbol”  Exit 04/09/13 37
  • 38.
    Parenthesis Checker  Else POP a symbol S from the Stack  If (S doesnot correspond to C)then  Print:”Error:Incorrect nesting of symbols”  Exit  Endif  Endif  Endif  End for 04/09/13 38
  • 39.
    Parenthesis Checker  If(stackis not empty)then  Print:”Error:Missing closing symbols(s)”  Else  Print:”Input expression is ok”  Endif  End 04/09/13 39
  • 40.
    Example of STACK  Many computer algorithms work best with stacks --- stacks are used for  remembering partially completed tasks, and  undoing (backtracking from) an action.  An example of 1. is described in the next section, where sub expressions of an arithmetic expression are remembered for later computation. Another example is presented in the next lecture, where we see how the Java Virtual Machine uses a stack to remember all of a program's methods that have been called but are not yet finished.  An example of 2. is the ``undo'' button on most text editors, which lets a person undo a typing error, or the ``back'' button on a web browser, which lets a user backtrack to a previous web page. Another example is a searching algorithm, which searches a maze and keeps a history of its moves in a stack. If the algorithm makes a false (bad) move, the move can be undone by retrieving the previous position from the stack. 04/09/13 40
  • 41.
    STACK Implementation  Static and dynamic data structures  A stack can be stored in:  • a static data structure  OR  • a dynamic data structure  Static data structures  These define collections of data which are fixed in size when the program is compiled.  An array is a static data structure.  Dynamic data structures  These define collections of data which are variable in size and structure. They are  created as the program executes, and grow and shrink to accommodate the data being  stored. 04/09/13 41
  • 42.
    TRANSPOSE OF SPARSE MATRIX  #include<stdio.h>  #include<conio.h>  // transpose for the sparse matrix  void main()  {  //clrscr();  int a[10][10],b[10][10];  int m,n,p,q,t,col;  int i,j;  printf("enter the no of row and columns :n");  scanf("%d %d",&m,&n); 04/09/13 42
  • 43.
    TRANSPOSE OF SPARSE MATRIX  // assigning the value of matrix  for(i=1;i<=m;i++)  {  for(j=1;j<=n;j++)  {  printf("a[%d][%d]= ",i,j);  scanf("%d",&a[i][j]);  }  } 04/09/13 43
  • 44.
    TRANSPOSE OF SPARSE MATRIX  printf("nn");  //displaying the matrix  printf("nnThe matrix is :nn");  for(i=1;i<=m;i++)  {  for(j=1;j<=n;j++)  {  printf("%d",a[i][j]);  }  printf("n");  } 04/09/13 44
  • 45.
    TRANSPOSE OF SPARSE MATRIX  t=0;  printf("nnthe non zero value matrix are :nn");  for(i=1;i<=m;i++)  {  for(j=1;j<=n;j++)  { // accepting only non zero value  if(a[i][j]!=0)  { 04/09/13 45
  • 46.
    TRANSPOSE OF SPARSE MATRIX  t=t+1;  b[t][1]=i;  b[t][2]=j;  b[t][3]=a[i][j];  } }  }  b[0][0]=m;  b[0][1]=n;  b[0][2]=t;  // displaying the matrix of non-zero value  printf("n");  For(i=0;i<=t;i++)  printf(“%d “,a[i][0],a[i][1],a[i][2]); 04/09/13 46
  • 47.
    TRANSPOSE OF SPARSE MATRIX  // transpose of the matrix  printf("nnthe transpose of the matrix :n ");  if(t>0)  {  for(i=1;i<=n;i++)  {  for(j=1;j<=t;j++)  {  if(b[j][2]==i)  {  a[q][1]=b[j][2]; a[q][2]=b[j][1];  a[q][3]=b[j][3]; q=q+1;  } } 04/09/13 }  } 47
  • 48.
    TRANSPOSE OF SPARSE MATRIX  for(i=0;i<=t;i++)  {  printf("a[%d %d %d %dn",i,a[i][1],a[i][2],a[i][3]);  }  getch();  } 04/09/13 48
  • 49.
    Tower of Hanoi(Anapplication of Recursion & Stack) This problem is not specified in terms of recursion but the recursive technique can be used to produce a logical solution .  Problem Definition:  There are three pegs A,B,& C exist, any number of disks (n) of different diameters are placed on peg A so that a larger disk is always below a smaller disk. 04/09/13 49
  • 50.
    Tower of Hanoi(Anapplication of Recursion & Stack)  The object is to move n disks to peg C ,using peg B as auxiliary.  Only the top disk on any peg may be moved to any other peg, and a larger disk may never rest on a smaller one.  Note:in general it requires f(n)=2n-1 moves 04/09/13 50
  • 51.
    Recursive solution totower of Hanoi problem  To move n disks from A to C using B as auxiliary: 1. If n==1 move the single disk from A to C and stop 04/09/13 51
  • 52.
    Recursive solution totower of Hanoi problem 2. Move the top n-1 disks from A to B , using C as auxiliary. 3. Move the remaining disks from A to C 4. Move the n-1 disks from B to C,using A as auxiliary. 04/09/13 52
  • 53.
    Recursive Implementation ofTower of Hanoi. main() { int n; scanf (“%d”, &n); towers (n, ’A’, ’C’ ,’B’); } 04/09/13 53
  • 54.
    towers(int n, charfrompeg, char topeg,char auxpeg) { If (n==1) { printf (“n %s %c %s %c”, “move disk 1 from peg “,frompeg, “to peg”, topeg); return; }04/09/13 54
  • 55.
    towers(n-1,frompeg,auxpeg,topeg) printf (“n %s%d %s %c %s %c”, “move disk”, n, “from peg”, frompeg, “to peg”, topeg); tower(n-1,auxpeg,topeg,frompeg); } 04/09/13 55