DATA STRUCTURES ( C++ )

DATA STRUCTURES ( C++ )

DATA STRUCTURES ( C++ )

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

1. DATA STRUCTURES ( C++ ) This PPT is Dedicated to my inner controller AMMA BHAGAVAN – ONENESS Founders. Developed by, EDITED BY, S.V.G.REDDY, M.Siva Naga Prasad Associate professor, student of M.tech(SE). Dept.of CSE, GIT, GITAM UNIVERSITY.

2. STACK USING ARRAYS • Let us take an array a[5] and take a variable top points to -1. • PUSH: • To INSERT the element in to stack using top. • Here we check for the OVERFLOW condition. • POP: • To RETRIEVE elements from the stack using top. • Here we check for the UNDERFLOW condition. • This concept is nothing but LIFO. SOURCE CODE: /* Program To Implement Stack using Array */ #include < iostream.h > #include < conio.h > #include < stdlib.h > #define MAX 10

3. class stack { private : int sp, a [ MAX ]; public : void init ( ); void push ( int ); void pop ( ); void display ( ); void count ( ); }; void stack :: init ( ) { sp = - 1; } void stack :: push ( int data) { if (sp = = ( MAX – 1 ) ) { cout<<"\n STACK OVERFLOW.......\n"; return; }

4. sp + + ; a [ sp ] = data; } void stack :: pop ( ) { if ( sp < 0 ) { cout<<"\n STACK UNDERFLOW.....\n"; return; } cout<<"\n POPED DATA IS ::: "<<a[sp]; sp - - ; } void stack :: display ( ) { cout << "\n DATA PRESENT IN A STACK IS ::: \n"; for ( int i = sp ; i > = 0 ; i - -) cout << a [ i ] <<"\t"; } void stack :: count ( ) { cout<<"\n NUMBER OF ELEMENTS IN A STACK ARE ::: "<<(sp+1); };

5. void main ( ) { stack ob; int data,ch; clrscr ( ); ob.init ( ); cout<<"\n**********STACK OPERATIONS**********\n"; cout<<"\n1.Push Operation"; cout<<"\n2.Pop Operation"; cout<<"\n3.Display Operation"; cout<<"\n4.Count Operation"; cout<<"\n5.Exit Operation"; cout<<"\n*************************************\n"; do { cout<<"\n ENTER YOUR CHOICE :: "; cin>>ch; switch ( ch ) { case 1:cout<<"\n ENTER ELEMENT TO BE INSERTED :::"; cin>>data; ob.push ( data ); break; case 2: ob.pop ( ); break; case 3: ob.display ( ); break; case 4:ob.count ( ); break; case 5: exit ( 0 ); defualt: cout<<"\nINVALID CHOICE "; } } while ( ch ! = 5 ); getch ( ); }

6. OUTPUT:

7. STACK USING LINKED LIST • We will create a linked list and insert an element ‘10’ and address as ‘0’.using top for the first node. • For second node insert data element ‘20’ and insert first node address at second node address field. • For third node insert data element ‘30’ and insert second node address at third node address field . after thirty we will stop the process . • If we want to print the elements 30,20,10 will be displayed, Thiss follows LIFO conceot.

8. Source code: #include<conio.h> #include<iostream.h> class st { public: struct node { int data; struct node *next; }*start,*temp,*top; st() { start=temp=top=NULL; } void create() { int d; cout<<"Enter data"; cin>>d; if(start==NULL) { start=new node; start->data=d;

9. start->next=NULL; top=start; } else { temp=new node; temp->data=d; temp->next=top; top=temp; } } void disp() { while(top!=NULL) { cout<<top->data<<"\t"; top=top->next; } } }; void main() { st ob; int ch; clrscr();

10. while(ch) { cout<<"Enter ur choice"; cout<<"0 STOP\n1 CREATE\n 2 READ"; cin>>ch; if(ch==1) ob.create(); else if(ch==2) ob.disp(); } } OUTPUT:

11. QUEUE USING ARRAYS • Here we will take an array a[5],and two variables front, rear points to -1. • WRITE: • Here will insert the element into the queue using rear variable. • Here check for the Overflow condition. • READ: • Here we will retrieve the elements from the queue using front variable. • Here check for the Underflow condition. • This follows the FIFO concept. rear 0 1 2 3 4 -1 front

12. SOURCE CODE: /* Program To Implement Queue using Array */ #include< iostream.h > #include< conio.h > #include< process.h > #define MAX 10 class queue { private : int front, rear, a [ MAX ]; public : void init ( ); void write ( int ); void read ( ); void count ( ); void display ( ); }; void queue :: init ( ) { front = rear = - 1; } void queue :: write ( int data) { if ( rear = = ( MAX - 1 ) ) cout<<"\n QUEUE IS OVERFLOW......"; else a [ + + rear ] = data; } void queue :: read ( ) { if( front = = rear ) cout<<"\n QUEUE IS UNDERFLOW....."; else cout<<"\n DELETED ELEMENT IN QUEUE IS :: "<<a[++front]; }

13. void queue :: count ( ) { cout<<"\n NUMBER OF ELEMENTS IN A QUEUE ARE :: "<<(rear-front); } void queue :: display ( ) { cout<<"\n ELEMENTS IN A QUEUE ARE:: "; for( int i = (front + 1); i < = rear; i + + ) cout<< a [ i ]<<"\t"; } void main ( ) { queue ob; int ch,data; clrscr ( ); ob.init ( ); cout<<"\n*****QUEUE OPERATIONS****\n"; cout<<"\n1.Write "; cout<<"\n2.Read "; cout<<"\n3.Count"; cout<<"\n4.Display"; cout<<"\n5.Exit"; cout<<"**************************\n";

14. do { cout<<"\n ENTER YOUR CHOICE :: "; cin>>ch; switch ( ch ) { case 1:cout<<"\n ENTER ELEMENT TO BE INSERTED IN QUEUE :: "; cin>>data; ob.write ( data ); break; case 2:ob.read ( ); break; case 3:ob.count ( ); break; case 4:ob.display ( ); break; case 5:exit ( 0 ); break; default :cout<<"\n INVALID CHOICE..."; } } while( ch ! = 5 ); getch ( ); }

15. OUTPUT:

16. Queue using linked list • Here we will create linked list with ‘n’ nodes one after another 10,20,30 etc. • If we try to print the elements it will display as 10,20,30. which follows FIFO concept.

17. SOURCE CODE: /* Program To Implement Queue using Linked List */ #include < iostream.h > #include< conio.h > #include < alloc.h > #define NULL 0 class node { int data; node *next; public: void create ( node *); void print ( node *); }; void node :: create (node *list) { cout<<"\n ENTER THE INPUT NO :: "; cout<<"\n TYPE 999 AT THE END :: "; cin>>list->data; if(list -> data = = 999) list->next = NULL; else { list -> next = new node; create( list -> next); } return; }

18. void node :: print (node *list) { if( list -> next ! = 0) { cout<< list->data; cout<<"->"; } else return; print( list -> next); } void main ( ) { node *head, ob; clrscr ( ); head = new node; ob.create ( head ); cout<<"\n QUEUE ELEMENTS ARE:: "; ob.print( head ); cout<<"999"; getch ( ); }

19. OUTPUT:

20. BINARY TREE USING RECURSION • A binary tree is a tree data structure in which each node has at most two children. Typically the child nodes are called left and right. Binary trees are commonly used to implement binary search trees and binary heaps. • Starting at the root of a binary tree, there are three main steps that can be performed and the order in which they are performed define the traversal type. • There are 3 types of traversals: • 1. Pre-Order • 2. In-Order • 3. Post-Order • To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: • Visit the root. • Traverse the left sub tree. • Traverse the right sub tree. • To traverse a non-empty binary tree in in order, perform the following operations recursively at each node, starting with the root node: • Traverse the left sub tree. • Visit the root. • Traverse the right sub tree. • To traverse a non-empty binary tree in post order, perform the following operations recursively at each node, starting with the root node: • Traverse the left sub tree. • Traverse the right sub tree. • Visit the root.

21. BINARY TREE: 15 7 22 Preorder:- 15,7,22 will be displayed . Post order:- 7,22,15 will be displayed . In order:- 7,15,22 will be displayed .

22. SOURCE CODE: /* Program To Implement Binary Tree Traversing */ #include < iostream.h > #include < conio.h > class bstree { public: struct node { int data; node *left; node *right; }*head; void create (node *); void inorder (node *); void preorder (node *); void postorder (node *); }; void* bstree:: create(node *list) { node *temp1,*temp2; intval; if(list = = NULL) { list = new node; cout<<"\nEnter Data Element:: "; cin>>list->data; list -> left = list -> right = NULL; } else

23. { cout<<"\n enter the data element"; cin>>val; temp1 = list; while( temp1 ! = NULL ) { temp2 = temp1; if(temp1 -> data > val) temp1 = temp1 -> left; else temp1 = temp1 -> right; } if(temp2 -> data > val) { temp2 -> left = new node; temp2 = temp2 -> left; temp2 -> data = val; temp2 -> left = temp2 -> right = NULL; } else { temp2 -> right = new node; temp2 = temp2 -> right; temp2 -> data = val; temp2 -> left = temp2 -> right = NULL; } } return (list); }

24. void bstree:: inorder(node *root) { if( ! root ) return; inorder( root -> left ); cout<<root->data<<"\t"; inorder( root -> right ); } void bstree::preorder(node*root) { if( ! root ) return; cout<<root->data<<”\t”; preorder( root -> left ); preorder( root -> right); } void bstree::postorder(node*root) { if( ! root) return; postorder( root -> left ); postorder( root -> right ); cout<<root->data<<”\t”; }

25. void main ( ) { node n,*head; head = NULL; clrscr ( ); cout<<"\nCreate A Binary Tree\n"; head=n.create ( head ); cout<<"\n the inorder traversal gives the following nodes"; n.inorder ( head ); getch ( ); } OUTPUT:

26. BINARY SEARCH TREE 15 7 22 • A tree having left child less than parent and right child grater than the parent. • Traversals are same as binary tree.

27. SOURCE CODE: /* Program to implement Binary search tree */ #include < iostream.h > #include < conio.h > class btree { private : struct btreenode { btreenode *leftchild ; int data ; btreenode *rightchild ; } *root; public: btree ( ) ; void buildtree ( int num ) ; static void insert ( btreenode **sr, int num ) ; void traverse ( ) ; static void inorder ( btreenode *sr ) ; static void preorder ( btreenode *sr ) ; static void postorder ( btreenode *sr ) ; static void del ( btreenode *sr ) ; ~btree ( ) ; } ;

28. btree :: btree ( ) { root = NULL ; } void btree :: buildtree ( int num ) { insert ( &root, num ) ; } void btree :: insert ( btreenode **sr, int num ) { if ( *sr == NULL ) { *sr = new btreenode ; ( *sr ) -> leftchild = NULL ; ( *sr ) -> data = num ; ( *sr ) -> rightchild = NULL ; return ; } else // search the node to which new node will be attached { // if new data is less, traverse to left if ( num < ( *sr ) -> data ) insert ( & ( ( *sr ) -> leftchild ), num ) ; else // else traverse to right insert ( & ( ( *sr ) -> rightchild ), num ) ; } return ; }

29. void btree :: traverse( ) { cout << "\nIN - ORDER TRAVERSAL :: " ; inorder ( root ) ; cout << "\nPRE - ORDER TRAVERSAL :: " ; preorder ( root ) ; cout << "\nPOST - ORDER TRAVERSAL :: " ; postorder ( root ) ; } void btree :: inorder ( btreenode *sr ) { if ( sr != NULL ) { inorder ( sr -> leftchild ) ; cout << "\t" << sr -> data ; inorder ( sr -> rightchild ) ; } else return ; } void btree :: preorder ( btreenode *sr ) { if ( sr != NULL ) { // print the data of a node cout << "\t" << sr -> data ; // traverse till leftchild is not NULL preorder ( sr -> leftchild ) ; // traverse till rightchild is not NULL preorder ( sr -> rightchild ) ; }

30. else return ; } void btree :: postorder ( btreenode *sr ) { if ( sr != NULL ) { postorder ( sr -> leftchild ) ; postorder ( sr -> rightchild ) ; cout << "\t" << sr -> data ; } else return ; } btree :: ~btree( ) { del ( root ) ; } void btree :: del ( btreenode *sr ) { if ( sr != NULL ) { del ( sr -> leftchild ) ; del ( sr -> rightchild ) ; } delete sr ; }

31. void main( ) { btree bt ; int req, i = 1, num ; clrscr(); cout << "\n SPECIFY THE NUMBER OF ITEMS TO BE INSERTED :: " ; cin >> req ; while ( i + + <= req ) { cout << "\n ENTER THE DATA :: " ; cin >> num ; bt.buildtree ( num ) ; } bt.traverse( ) ; getch(); } OUTPUT:

32. SPARSE MATRIX AIM: Write a program in C++ to implement ADDITION and MULTIPLICTION of two SPARSE matrixes. THEORY: If a lot of elements from a matrix have a value 0 then the matrix is known as SPARSE MATRIX. If the matrix is sparse we must consider an alternate way of representing it rather the normal row major or column major arrangement. This is because if majority of elements of the matrix are 0 then an alternative through which we can store only the non-zero elements and keep intact the functionality of the matrix can save a lot of memory space. Example: Sparse matrix of dimension 7 x 7. COLUMNS 0 1 2 3 4 5 6 0 0 0 0 -5 0 0 0 1 0 4 0 0 0 0 7 2 0 0 0 0 9 0 0 ROWS 3 0 3 0 2 0 0 0 4 1 0 2 0 0 0 0 5 0 0 0 0 0 0 0 6 0 0 8 0 0 0 0

33. A common way of representing non-zero elements of a sparse matrix is the 3-tuple forms. In this form each non-zero element is stored in a row, with the 1st and 2nd element of this row containing the row and column in which the element is present in the original matrix. The 3rd element in this row stores the actual value of the non-store element. For example 3-tuple representation of the sparse matrix as shown in below. • intspmat[10][3]={ • 7, 7, 9, • 0, 3, -5, • 1, 1, 4, • 1, 6, 7, • 2, 4, 9, • 3, 1, 3, • 3, 3, 2, • 4, 0, 11, • 4, 2, 2, • 6, 2, 8 • }

34. SOURCE CODE: /*Program to demonstrate addition and multiplication of Two Sparse Matrix */ #include < iostream.h > #include < conio.h > #define x 25 class sparce { private: int a [ x ] [ x ], b [ x ] [ x ], c [ x ] [ x ], m, n, p, q; public: void init ( ); void input ( ); void add ( ); void mul ( ); void display ( int [25][25], int, int ); void convert( int [25][25], int, int ); }; void sparce :: init ( ) { int i, j; for(i = 0; i < x;i + + ) for( j = 0; j < x; j + +) c [ i ] [ j ] = 0; }

35. void sparce :: input() { int i,j; cout<<"\nEnter order Of First matrix::"; cin>>m>>n; cout<<"\nEnter order Of Second matrix::"; cin>>p>>q; cout<<"\nEnter"<<m*n<<"Elements Into First Matrix\n"; for(i=0;i<m;i++) for( j = 0; j < n; j + + ) cin>> a[ i ] [ j ]; cout<<"\nEnter"<<p*q<<"Elements Into Second Matrix\n"; for(i = 0; i < p ; i + + ) for ( j = 0; j < q ; j + + ) cin>>b [ i ] [ j ]; } void sparce :: add ( ) { int i, j; if( m = = p && n = = q ) { for( i = 0 ; i < m ; i + + ) for( j = 0; j < n; j + + ) c[ i ] [ j ] = a [ i ][ j ] + b [ i ] [ j ]; convert( c, m, n); } else cout<<"\nAddition Is Not Possible"; }

36. void sparce :: mul ( ) { int i, j, k; if(n = = p) { for( i = 0; i < m; i + +) for( j = 0; j < q; j + + ) for( k = 0; k < n; k + + ) c[ I ] [ j ] + = a [ I ] [ k ] * b [ k ] [ j ]; convert(c, m, n); } else cout<<"\n Multiplecation Is Not Possible"; } void sparce :: display(int c[25][25], int m, int n) { int i,j; for( i = 0 ;i < m; i + + ) { for( j = 0 ; j < n ; j + + ) cout<<c [ i ] [ j ]<<"\t"; cout<<"\n"; } }

37. void sparce :: convert(int c[25][25], int m, int n) { inti, j, k = 1,t = 0; int sp[25][25]; for( i = 0 ; i < m ; i + +) for( j = 0 ; j < n ; j + + ) if(c [ i ] [ j ] ! = 0 ) { sp [ k ] [ 0 ] = i; sp [ k ] [ 1 ] = j; sp [ k ] [ 2 ] = c [ i ] [ j ]; k + + ; t + + ; } sp[ 0 ] [ 0 ] = m; sp[ 0 ] [ 1 ] = n; sp[ 0 ] [ 2 ] = t; display( sp, k, 3); } void main ( ) { sparce ob; clrscr ( ); ob.init ( ); ob.input ( ); cout<<"\nAddition of Two Sparce Matrix\n"; ob.add ( ); ob.init ( ); cout<<"\nMultiplecation Of Two Sparce Matrix\n"; ob.mul ( ); getch ( ); }

38. OUTPUT:

39. INFIX TO POSTFIX CONVERTIONic • Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression P. • Step 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. • 5 If an operator * is encountered , then: a. repeatedly pop from stack and top each operator (on the top of stack ) which has the same precedence or higher precedence than * . b. Add * to stack. • 6. If a right parenthesis is encountered , then: a. repeatedly from stack and add to P each operator (on the top of stack) until a left parenthesis is encountered. b. remove the left parenthesis [ Do not add the left parenthesis top] [End of if structure] [End of step 2 loop] • 7. Exit

40. (A+(B*C-(D/E^F)*G)*H)

41. SOURCE CODE: /* Program To implement infix to postfix Expression */ #include < iostream.h > #include< process.h > #include < conio.h > char stack[30], postfix[30], infix[30]; int top = - 1; int pri( char x ) { int value; switch ( x ) { case ')': value=0; break; case '+': case '-': value=1; break; case '*': case '/': case '%': value=2; break; case '^': value=3; break; case '(': value=4; break; default: cout<<"INVALID EXPRESSION !!!!!!"; exit(1); } return value; }

42. void push ( char x ) { top = top + 1; stack [top] = x; } char stacktop ( ) { return stack [ top ]; } int isalnum (char x) { return ( (x>='0' && x<='9') ||( x>='a' && x<='z') || ( x>='A' && x<='Z')); } char pop( ) { return stack[top - - ]; }

43. void intopost(char infix[ ], char postfix[ ]) { int i, j=0; char c, pc; for ( i = 0; ( c = infix[ i ] ) != '\0' ; i + +) { if ( isalnum (c) ) postfix [ j + + ] = c; else { while ( top ! = - 1 && (pri (stacktop () ) >= pri (c) ) ) { If ( stacktop( ) = = '(' && c! = ')' ) break; if ( stacktop( ) = = '(' && c = =')' ) { pop () ; break; } pc = pop( ); if ( pc! = '(' ) postfix [ j + + ] = pc; else break; } if( c! = ')' ) push ( c ); } } while( top ! = -1 ) postfix[ j + + ] = pop( ); postfix [ j ] = '\0'; }

44. void main ( ) { clrscr ( ); cout<<"ENTER INFIX EXPRESSION ::\n\n\t\t\t"; cin>>infix; intopost( infix, postfix ); cout<<"POSTFIX EXPRESSION ::\n\n\t\t\t "; cout<<postfix; getch ( ); } OUTPUT:

45. POSTFIX EVALUATION • THEORY: • Reverse Polish notation is a mathematical notation wherein every operator follows all of its operands. It is also known as Postfix notation and is parenthesis free. • In Reverse Polish notation the operators follow their operands; for instance, to add three and four, one would write “3 4 +” rather than “3 + 4”. If there are multiple operations, the operator is given immediately after its second operand; so the expression written “3 − 4 + 5” in conventional infix notation would be written “3 4 − 5 +” in RPN: first subtract 4 from 3, then add 5 to that. • Infix Expression: Any expression in the standard form like "2*3-4/5" is an Infix(In order) expression.Postfix Expression: The Postfix(Post order) form of the above expression is "23*45/-". • Postfix Evaluation: In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows: • Scan the Postfix string from left to right. • Initialize an empty stack. • If the scanned character is an operand, add it to the stack. If the scanned character is an operator, there will be at least two operands in the stack • If the scanned character is an Operator, then we store the top most element of the stack(topStack) in a variable temp. Pop the stack. Now evaluate topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and Push retVal into the stack. • Repeat this step till all the characters are scanned. • After all characters are scanned, we will have only one element in the stack. Return topStack.

46. Example: Postfix String: 1 2 3 * + 4 - . Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that order. Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the stack and perform the "*" operation with the two operands. The second operand will be the first element that is popped. The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.

47. Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the stack and perform the "+" operation with the two operands. The second operand will be the first element that is popped. The value of the expression(1+6) that has been evaluated(7) is pushed into the stack. Next character scanned is "4", which is added to the stack. Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the stack and perform the "-" operation with the two operands. The second operand will be the first element that is popped.

48. The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. Now, since all the characters are scanned, the remaining element in the stack (there will be only one element in the stack) will be returned. End result: Postfix String : 1 2 3 * + 4 - Result : 3

49. SOURCE CODE: /*Program To Evaluate Postfix Expression */ #include < iostream.h > #include < conio.h > #include < math.h > #include < string.h > class postfix { private: int stack[50], len, top; char post[50]; public: postfix ( ); void push ( int ); int pop ( ); intpfix ( ); }; void postfix :: postfix ( ) { top = - 1; } int postfix :: pfix ( ) { int a, b, i, temp; cout<<"\nEnter Postfix Expression::"; cin>>post; len = strlen ( post ); post [ len] = '#';