{"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 0, "text": "MODULE II-STACKS, QUEUES, RECURSION Dr. Ganga Holi, Professor & Head, ISE Dept. Global Academy of Technology Dept. of Information Science & Engineering [COMPANY NAME] [Company address] Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 1 Global Academy of Technology Dept. of Information Science & Engineering Data Structure Notes On Module II Stacks, Queues & Recursion Dr. Ganga Holi, Professor & Head Contents Stacks .......................................................................................................................................................... 1 Array representation of stacks ................................................................................................................. 2 Stack Operations ........................................................................................................................................ 2 Algorithms for stack operations ................................................................................................................ 2 Applications of Stack ................................................................................................................................. 4 Evaluation of Postfix expression .............................................................................................................. 4 Conversion to Infix expression to Postfix expression ........................................................................... 5 Multiple stacks ............................................................................................................................................ 8 Recursion .................................................................................................................................................... 9 Rules ...................................................................................................................................................... 11 Queue Data structure .............................................................................................................................. 13 Basic features of Queue .......................................................................................................................... 14 Applications of Queue ............................................................................................................................. 14 Disadvantage Simple Queue .................................................................................................................. 17 Circular Queue .......................................................................................................................................... 17 Circular Queue Program ......................................................................................................................... 20 Dequeues- Double Ended Queues ....................................................................................................... 21 Output Restricted Double Ended Queue .............................................................................................. 22 Priority Queue ......................................................................................................................................... 22 Basic Operations .................................................................................................................................... 23 Using single array ................................................................................................................................... 23 Using Multiple arrays ............................................................................................................................... 25 Related Questions on Queue & Stacks ................................................................................................ 26 Related Questions on Stacks ................................................................................................................. 26 Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 1 Stacks Definition: A stack is linear Data Sturcture in which items are added (pushed, inserted) and removed(pop, deleted) from one end called top. A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the stacks only two operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. Push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top. Given a stack S=(a0,a1, \u2026.an-1), we say a0 is the bottom element, an-1 is the top element and ai , is on the top of element ai-1 , 0=0;i--) printf(\"%d\\n\",stack[i]); } int topStack() { return(stack[top]; } // Complete program for stack operations #include #define max_size 5 int stack[max_size],top=-1; void push(); void pop(); void display(); int main() { int choice; while(1) { printf(\"\\n\\n--------STACK OPERATIONS-----------\\n\"); printf(\"1.Push\\n\"); printf(\"2.Pop\\n\"); printf(\"3.Display\\n\"); printf(\"4.Exit\\n\"); printf(\"\\nEnter your choice:\\t\"); scanf(\"%d\",&choice); switch(choice) { case 1 : printf(\"Enter the element to be inserted:\\t\"); scanf(\"%d\",&item); push(ele); break; case 2 : ele=pop(); if(ele==-1) printf(\"stack Underflow\\n\u201d); else printf(\"Poped element =%d\\n\u201d, ele); break; case 3 : display(); break; case 4 : return 0; default : printf(\"\\nInvalid choice:\\n\") ; break; } Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 4 } return 0; } Applications of Stack \u2022 The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack. \u2022 Another application is an \"undo\" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack. \u2022 Evaluation of Expressions \u2022 Conversion from Infix to Postfix, prefix \u2022 Language processing: o space for parameters and local variables is created internally using a stack. o compiler's syntax check for matching braces is implemented by using stack. o support for recursion Infix expression- The expression in which operator is placed in between operands Ex. a+b Polish Notation- names after the Polish Mathematician Jan Lukasiewiez, refers to the expression in which the operator is placed before the operands also called prefix expression. Ex. +ab Reverse Polish Notation- refers to the expression in which the operator is placed after the operands also called postfix expression or suffix Expression. Ex. ab+ Evaluation of Postfix expression In high level languages, infix notation cannot be used to evaluate expressions. Instead compilers typically use a parenthesis free notation to evaluate the expression. A common technique is to convert a infix notation into postfix notation, then evaluating it. Before knowing the function that translates infix expression to postfix expression, we need to know how to evaluate the postfix expression. 45+ will be evaluate as 4+5=9 To evaluate an expression we"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 2, "text": "evaluate the expression. A common technique is to convert a infix notation into postfix notation, then evaluating it. Before knowing the function that translates infix expression to postfix expression, we need to know how to evaluate the postfix expression. 45+ will be evaluate as 4+5=9 To evaluate an expression we make single left to right scan (read) of it. We place the operands on a stack until we find an operator. We then remove, from the stack, correct number of operands for the operator, perform operation, and place the result back on the stack. We continue until we reach the end of the expression. We remove the result top of the stack. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 5 Example3. Postfix Stack 234*+ 34*+ 2 4*+ 2 3 *+ 2 3 4 (3*4=12) + 2 12 (2+12=24) 24 Algorithm/ Function to evaluate Postfix expression int op(int op1,char sym,int op2) //op=evaluate { switch(sym) { case '+': return op1+op2; case '-': return op1-op2; case '*': return op1*op2; case '/': return op1/op2; case '%': return op1%op2; case '^': case '$': return pow(op1,op2); } return 0; } void evaluatePostfix() { for(i=0;i='0' && sym<='9') s[++top]=sym-'0'; else { op2=s[top--]; op1=s[top--]; s[++top]=op(op1,sym,op2); } } printf(\"\\nThe result is %d\",s[top]); } Conversion to Infix expression to Postfix expression Infix to Postfix Notation. Normally you will code your expressions in the programmes using infix notation, but compiler understands and uses only postfix notation and hence it has to convert infix notation to post fix notation. For this activity, stack data structure is used. We will consider following binary operators and their precedence rules: ^ Exponentiation Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 6 * / Multiplication and Division. Both have same priority-- Execution is from left to right. + - Addition and Subtraction. Both have same priority--- Execution is from left to right. Other Operators : order is from left to right Example D+E-G means (D+E)-G Let us solve a problem Infix notation : A +B * C \u2013 D Based on priorities of operators, parenthesize the expression. You know, the priority for the expression given is ( * or / ) and followed by (+ or -). ( ( A + ( B * C ) ) \u2013 D ) Check your brackets are correct and opening and closing brackets match. Opening brackets = closing brackets = 3 Step 3. Number your brackets starting from Right Hand side. Give the same number to governing bracket on left hand side. ( ( A + ( B * C ) ) \u2013 D ) 1 2 3 3 2 1 Post Fix Notation : A B C * + D - Example: Infix Expression -- A + B * C - D / E S.No Infix Stack(top) Postfix 1. A + B * C -D / E # 2. + B * C -D / E # A 3. B * C -D / E"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 3, "text": "B C * + D - Example: Infix Expression -- A + B * C - D / E S.No Infix Stack(top) Postfix 1. A + B * C -D / E # 2. + B * C -D / E # A 3. B * C -D / E # + A 4. *C -D / E #+ AB 5. C -D / E #+* AB 6. -D / E #+* ABC 7. -D / E #+ A B C * 8. D / E #+- A B C * 9. / E #+- A B C * D 10. E #+-/ A B C * D 11. #+-/ A B C * D E 12. #+- A B C * D E / 13. #+ A B C * D E /- 14. # A B C * D E/- + Example 2: A * B - ( C + D ) + E S.No Infix Stack(bot->top) Postfix 1. A * B - ( C - D ) + E empty empty 2. * B - ( C + D ) + E empty A 3. B - ( C + D ) + E * A 4. - ( C + D ) + E * A B 5. - ( C + D ) + E empty A B * 6. ( C + D ) + E - A B * Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 7 7. C + D ) + E - ( A B * 8. + D ) + E - ( A B * C 9. D ) + E - ( + A B * C 10. ) + E - ( + A B * C D 11. + E - A B * C D + 12. + E empty A B * C D + - 13. E + A B * C D + - 14. + A B * C D + -E 15. Empty A B * C D + -E+ Algorithm or function for conversion infix to postfix expression void postfix(void) { // assuming variables are declared as global char ch; int i; push('#'); while ((ch = infx[i++]) != '\\0') { if (ch == '(') push(ch); else if (isalnum(ch)) pofx[k++] = ch; else if (ch == ')') { while (s[top] != '(') pofx[k++] = pop(); elem = pop(); /* Remove ( */ } else /* Operator */ { while (pr(s[top]) >= pr(ch)) pofx[k++] = pop(); push(ch); } } while (s[top] != '#') /* Pop from stack till empty */ pofx[k++] = pop(); pofx[k] = '\\0'; /* Make pofx as valid string */ printf(\"Given Infix Expn: %s Postfix Expn: %s\\n\", infx, pofx); } // pr() is a function for finding the operator precedence value int pr(char elem) /* Function for precedence */ { switch (elem) { case '#' : return 0; Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 4, "text": "Infix Expn: %s Postfix Expn: %s\\n\", infx, pofx); } // pr() is a function for finding the operator precedence value int pr(char elem) /* Function for precedence */ { switch (elem) { case '#' : return 0; Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 8 case '(' : return 1; case '+' : case '-' : return 2; case '*' : case '/' : case '%' : return 3; case '^': return 4; } } Exercise Problems from Sahni 1. Write postfix and prefix expression of the following expressions a. A*b*c b. \u2013a+b-c+d c. a*(-b)+c -\u2192 ans: ab-*c+ here no. of operators equal to no. of operands. So there has to be one unary operator\u2026 So \u2013b will be evaluated first, then * will be performed, then +. d. a&&b||c||!(e>f) ( assuming C precedence Refer C text book) Multiple stacks Multiple stacks can be implemented using multiple arrays, one array to represent on stack. Multiple stacks can be implemented using single array. Single array can be used to represent two stacks: one will go from beginning from starting towards end and second stack will go in opposite direction. top S1[top]=-1 stack empty condition if(top==-1) S2[bot]=N stack empty condition if(bot==N) Stack full if (top==bot) for both Stack 1 :Push -- S1[++top]=ele Pop -\u2192 ele=S1[top--] Stack 2 :Push -- S2[--bot]=ele Pop -\u2192 ele=S2[top++] Single array can be used to represent multiple stacks by dividing into equal number of parts. i=0 I=N\u2026\u2026\u2026.. I=2N\u2026\u2026\u2026.. I=3N- I=3N\u2026\u2026\u2026.. \u2026\u2026\u2026. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 9 \u2026\u2026\u2026\u2026\u2026.i0 the n!=n.(n-1)! fact(n) { if(n<1) return 1; else return(n*fact(n-1)); } Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 10 Fibonacci Sequence Fibonacci series 0,1,1,2,3,5,8,13,21,\u2026.. 1. if n=0 or n=1, then Fn =n 2. if n>1 then Fn=Fn-1+Fn-2 fib(n) { if(n==0) return 0; if(n==1) return 1; else return( fib(n-1)+fib(n-2)); } Ackermann\u2013P\u00e9ter function The two-argument Ackermann\u2013P\u00e9ter function, is defined as follows for nonnegative integers m and n: \ud835\udc68(\ud835\udc8e, \ud835\udc8f) = { \ud835\udc8f+ \ud835\udfcf \ud835\udc8a\ud835\udc87\ud835\udc8e= \ud835\udfce"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 5, "text": "0,1,1,2,3,5,8,13,21,\u2026.. 1. if n=0 or n=1, then Fn =n 2. if n>1 then Fn=Fn-1+Fn-2 fib(n) { if(n==0) return 0; if(n==1) return 1; else return( fib(n-1)+fib(n-2)); } Ackermann\u2013P\u00e9ter function The two-argument Ackermann\u2013P\u00e9ter function, is defined as follows for nonnegative integers m and n: \ud835\udc68(\ud835\udc8e, \ud835\udc8f) = { \ud835\udc8f+ \ud835\udfcf \ud835\udc8a\ud835\udc87\ud835\udc8e= \ud835\udfce \ud835\udc68(\ud835\udc8e\u2212\ud835\udfcf, \ud835\udfcf) \ud835\udc8a\ud835\udc87 \ud835\udc8e> \ud835\udfce \ud835\udc82\ud835\udc8f\ud835\udc85 \ud835\udc8f= \ud835\udfce \ud835\udc68(\ud835\udc8e\u2212\ud835\udfcf, \ud835\udc68(\ud835\udc8e, \ud835\udc8f\u2212\ud835\udfcf)) \ud835\udc8a\ud835\udc87 \ud835\udc8e> \ud835\udfce \ud835\udc82\ud835\udc8f\ud835\udc85 \ud835\udc8f> \ud835\udfce A(0,1)=2 A(1,1)=A(m-1,A(m,n-1))=A(0,A(1,0))=A(0,A(0,1))=A(0,2)=3 A(2,1)=A(1,A(2,0))=A(1,A(1,1))=A(1,3)=A(0,A(1,2))=A(0,A(0,A(1,1))) =A(0,A(0,3))=A(0,4)=5 It grows very fast and non primitive recursive function. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 11 Tower of Hanoi Tower of Hanoi, is a mathematical puzzle which consists of three tower (pegs) and more than one rings; as depicted below \u2212 These rings are of different sizes and stacked upon in ascending order i.e. the smaller one sits over the larger one. There are other variations of puzzle where the number of disks increase, but the tower count remains the same. Rules The mission is to move all the disks to some another tower without violating the sequence of arrangement. The below mentioned are few rules which are to be followed for tower of hanoi \u2212 \u2022 Only one disk can be moved among the towers at any given time. \u2022 Only the \"top\" disk can be removed. \u2022 No large disk can sit over a small disk. Tower of hanoi puzzle with n disks can be solved in minimum 2n\u22121 steps. This presentation shows that a puzzle with 3 disks has taken 23\u22121 = 7 steps. Step 1 \u2212 Move n-1 disks from source to temp Step 2 \u2212 Move nth disk from source to dest Step 3 \u2212 Move n-1 disks from temp to dest N=1 Step 1 \u2212 Move nth disk from source(A) to dest(C) N=2 Step 1 \u2212 Move n-1=1 disk from source(A) to temp(B) Step 2 \u2212 Move nth =2 disk from source(A) to dest(C) Step 3 \u2212 Move n-1=1 disk from temp(B) to dest(C) Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 12 void tower(n, source, temp, dest) { if(n == 0) printf(\u201cmove %d disk from %c to %c\u201d, source,dest); else { tower(n - 1, source, dest,temp) // Step 1 printf(\u201cmove %d disk from %c to %c\u201d, source,dest); // Step 2 tower(n - 1, temp, source, dest) // Step 3 } } Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 13 Queue Data structure In our daily life, to catch a bus, to with draw money from ATM or to buy a cinema ticket, we form a queue. Queue is a first in first out FIFO linear data structure Queue is an important data structure for computer applications even. Queue is linear data structure in which deletion of element can take place only at one end called the front end and insertion can take place at the other end called the rear. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 14"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 6, "text": "computer applications even. Queue is linear data structure in which deletion of element can take place only at one end called the front end and insertion can take place at the other end called the rear. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 14 Basic features of Queue 1. Like Stack, Queue is also an ordered list of elements of similar data types. 2. Queue is a FIFO( First in First Out ) structure. 3. Once a new element is inserted into the Queue, all the elements inserted before the new element in the queue must be removed, to remove the new element. 4. peek( ) function is oftenly used to return the value of first element without dequeuing it. Applications of Queue Queue, as the name suggests is used whenever we need to have any group of objects in an order in which the first one coming in, also gets out first while the others wait for there turn, like in the following scenarios : 1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc. 2. In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a service representative is free. 3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive, First come first served. Implementation of Queue Queue can be implemented using an Array, Stack or Linked List. The easiest way of implementing a queue is by using an Array. Initially the head(FRONT) and the tail(REAR) of the queue points at the first index of the array (starting the index of array from 0). As we add elements to the queue, the rear keeps on moving ahead, always Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 15 pointing to the position where the next element will be inserted, while the front remains at the first index. When we remove element from Queue, we can follow two possible approaches (mentioned [A] and [B] in above diagram). In [A] approach, we remove the element at front position, and then one by one move all the other elements on position forward. In approach [B] we remove the element from front position and then move front to the next position. In approach [A] there is an overhead of shifting the elements one position forward every time we remove the first element. In approach [B] there is no such overhead, but whenever we move head one position ahead, after removal of first element, the size on Queue is reduced by one space each time. Rear=-1=-1 Front=0 Front=0 Front=0 Rear=4 Rear=0 Front=1 Front=1 Rear=4 Rear=3 Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 16 /*SIMPLE QUEUE Design, Develop and Implement a menu driven Program in C for the following operations on Simple QUEUE of Characters (Array Implementation of Queue with maximum size MAX) a. Insert an"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 7, "text": "Front=1 Front=1 Rear=4 Rear=3 Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 16 /*SIMPLE QUEUE Design, Develop and Implement a menu driven Program in C for the following operations on Simple QUEUE of Characters (Array Implementation of Queue with maximum size MAX) a. Insert an Element on to QUEUE b. Delete an Element from QUEUE c. Demonstrate Overflow and Underflow situations on QUEUE d. Display the status of QUEUE e. Exit Support the program with appropriate functions for each of the above operations */ #include #define SIZE 5 int i,rear=-1,front=0,option,j; char q[SIZE]; int qFull() { if(rear==SIZE-1) return 1; else return 0; } int qEmpty() { if(front>rear) return 1; else return 0; } void enqueue(char ch) { if(qFull()) { printf(\" Queue overflow\\n\"); return; } q[++rear]=ch; return; } char dequeue() { return q[front++]; } void display() { int i; for(i=front;i<=rear;i++) printf(\"%c \",q[i]); printf(\"\\n\"); } Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 17 int main() { char ch; for(;;) { printf(\"\\n SIMPLE QUEUE\\n\"); printf(\"1.Insert\\n\"); printf(\"2.Delete\\n\"); printf(\"3.Display\\n\"); printf(\"4.Exit\"); printf(\"\\nEnter your option:\"); scanf(\"%d\",&option); switch(option) { case 1 : printf(\"\\nEnter the char:\"); ch=getchar(); ch=getchar(); enqueue(ch); break; case 2 : if(qEmpty()) printf(\"\\nQ is empty\\n\"); else printf(\"\\nDeleted item is: %c\",dequeue()); break; case 3 : if(qEmpty()) printf(\"\\nQ is empty\\n\"); else display(); break; default : return 0; } } } Disadvantage Simple Queue When the first element is serviced, the front is moved to next element. However, the position vacated is not available for further use. Thus, we may encounter a situation, wherein program shows that queue is full, while all the elements have been deleted are available but unusable, though empty. Circular Queue In a standard queue data structure re-buffering problem occurs for each dequeue operation. To solve this problem by joining the front and rear ends of a queue to make Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 18 the queue as a circular queue. Circular queue is a linear data structure. It follows FIFO principle. \u2022 In circular queue the last node is connected back to the first node to make a circle. \u2022 Elements are added at the rear end and the elements are deleted at front end of the queue \u2022 Both the front and the rear pointers points to the beginning of the array. \u2022 It is also called as \u201cRing buffer\u201d. Circular Queue can be created in three ways they are \u00b7 Using linked list \u00b7 Using arrays In arrays the range of a subscript is 0 to n-1 where n is the maximum size. To make the array as a circular array by making the subscript 0 as the next address of the subscript n-1 by using the formula subscript = (subscript +1) % maximum size. In circular queue the front and rear pointer are updated by using the above formula. The following figure shows circular array: Queue shown in above figure is full. Queue shown in above figure has one empty slot at the"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 8, "text": "by using the formula subscript = (subscript +1) % maximum size. In circular queue the front and rear pointer are updated by using the above formula. The following figure shows circular array: Queue shown in above figure is full. Queue shown in above figure has one empty slot at the beginning, as first element is deleted from the queue. Below figure shows two elements deletion and queue has two empty slots at the beginning. Now element can be inserted from the beginning making use of rear pointer pointing to beginning location. R F 20 30 40 50 60 70 R F 30 40 50 60 70 R F Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 19 Figure shown below shows that element 80 is added at the beginning location and rear is now pointing to 0th location. Every time rear is incremented by the value =(rear+1)%SIZE. Every time front is incremented by the value=(front+1)%SIZE. Algorithm for Enqueue operation using array Step 1. start Step 2. if (front == (rear+1)%max) Print error \u201ccircular queue overflow \u201c Step 3. else { rear = (rear+1)%max Q[rear] = element; If (front == -1 ) f = 0; } Step 4. stop Algorithm for Dequeue operation using array Step 1. start Step 2. if ((front == rear) && (rear == -1)) Print error \u201ccircular queue underflow \u201c Step 3. else { element = Q[front] If (front == rear) front=rear = -1 Else Front = (front + 1) % max } Step 4. stop 80 30 40 50 60 70 R F Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 20 Circular Queue Program Design, Develop and Implement a menu driven Program in C for the following operations on Circular QUEUE of Characters (Array Implementation of Queue with maximum size MAX) a. Insert an Element on to Circular QUEUE b. Delete an Element from Circular QUEUE c. Demonstrate Overflow and Underflow situations on Circular QUEUE d. Display the status of Circular QUEUE e. Exit Support the program with appropriate functions for each of the above operations */ #include #include #include #define SIZE 5 int q[SIZE],rear=-1,front=0,option,count=0; int qFull() { if(count==SIZE) return 1; else return 0; } int qEmpty() { if(count==0) return 1; else return 0; } void enqueue(char ch) { if(qFull()) { printf(\" Queue overflow\\n\"); return; } rear=(rear+1)%SIZE; q[rear]=ch; count++; printf(\" rear=%d count=%d\\n\",rear,count); return; } char dequeue() { char c; c=q[front]; front=(front+1)%SIZE; count--; return c; } void display() { int i; j=front; for(i=0;i #include #include #include #define MAX 6 int intArray[MAX]; int itemCount = 0; int peek(){ return intArray[itemCount - 1]; } bool isEmpty(){ return itemCount == 0; } bool isFull(){ return itemCount == MAX; } int size(){ return itemCount; } void insert(int data){ int i = 0; if(!isFull()){ // if queue is empty, insert the data if(itemCount == 0){ intArray[itemCount++] = data; Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 24 }else{ // start from the right end of the queue for(i = itemCount - 1; i >= 0; i-- ){ // if data is larger, shift existing item to right end if(data > intArray[i]){ intArray[i+1] = intArray[i]; }else{ break; } } // insert the data intArray[i+1] = data; itemCount++; } } } int removeData(){ return intArray[--itemCount]; } int main() { /* insert 5 items */ insert(3);"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 10, "text": ">= 0; i-- ){ // if data is larger, shift existing item to right end if(data > intArray[i]){ intArray[i+1] = intArray[i]; }else{ break; } } // insert the data intArray[i+1] = data; itemCount++; } } } int removeData(){ return intArray[--itemCount]; } int main() { /* insert 5 items */ insert(3); insert(5); insert(9); insert(1); insert(12); // ------------------ // index : 0 1 2 3 4 // ------------------ // queue : 12 9 5 3 1 insert(15); // --------------------- // index : 0 1 2 3 4 5 // --------------------- // queue : 15 12 9 5 3 1 if(isFull()){ printf(\"Queue is full!\\n\"); } // remove one item int num = removeData(); printf(\"Element removed: %d\\n\",num); // --------------------- // index : 0 1 2 3 4 // --------------------- // queue : 15 12 9 5 3 // insert more items Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 25 insert(16); // ---------------------- // index : 0 1 2 3 4 5 // ---------------------- // queue : 16 15 12 9 5 3 // As queue is full, elements will not be inserted. insert(17); insert(18); // ---------------------- // index : 0 1 2 3 4 5 // ---------------------- // queue : 16 15 12 9 5 3 printf(\"Element at front: %d\\n\",peek()); printf(\"----------------------\\n\"); printf(\"index : 5 4 3 2 1 0\\n\"); printf(\"----------------------\\n\"); printf(\"Queue: \"); while(!isEmpty()){ int n = removeData(); printf(\"%d \",n); } } Using Multiple arrays Multiple arrays are used to implement the priority queue. Array number represents the priority value. If the priority of the element is 1 then inserted that element in Q1,if the priority of the element is 2 then inserted that element in Q2, and so on. But deletion will happen from the highest priority queue first. All the elements of the highest priority queue will be deleted first, and then second priority queue elements and so on. Using linked list we can implement the Priority Queue. Two dimensional arrays can also be used to represent Priority Queue. Row represents the Priority value and order of arrival of the elements. Size of the array depends on the Priority Value. Col\u2192 Row | V 1 2 3 4 5 6 Q P -1 Q P H Q P -2 A B C D E Q P -3 T P R M Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 26 Related Questions on Queue & Stacks \u2022 What is stack? What are the operations on stack?> \u2022 What is the recursion? What are two important criteria for recursive functions? \u2022 How does rear and front work in circular queue in C language? \u2022 What are the applications of queues and stacks? \u2022 How is priority queue implemented in C? \u2022 Can we use an array to create a circular queue? \u2022 What is the application of queues in computer science? \u2022 What is the advance application of circular queue? \u2022 What is queue and a circular queue? \u2022 How does rear and"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 11, "text": "How is priority queue implemented in C? \u2022 Can we use an array to create a circular queue? \u2022 What is the application of queues in computer science? \u2022 What is the advance application of circular queue? \u2022 What is queue and a circular queue? \u2022 How does rear and front work in circular queue in C language? \u2022 What is dequeue? How to insert and delete from dequeue. \u2022 Describe the priority queue. How do we implement the priority queues? Related Questions on Stacks 1. Entries in a stack are \"ordered\". What is the meaning of this statement? o A. A collection of stacks can be sorted. o B. Stack entries may be compared with the '<' operation. o C. The entries must be stored in a linked list. o D. There is a first entry, a second entry, and so on. 2. The operation for adding an entry to a stack is traditionally called: o A. add o B. append o C. insert o D. push 3. The operation for removing an entry from a stack is traditionally called: o A. delete o B. peek o C. pop o D. remove 4. Which of the following stack operations could result in stack underflow? o A. is_empty o B. pop o C. push o D. Two or more of the above answers 5. Which of the following applications may use a stack? o A. A parentheses balancing program. o B. Keeping track of local variables at run time. o C. Syntax analyzer for a compiler. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 27 o D. All of the above. 6. Consider the following pseudocode: declare a stack of characters while ( there are more characters in the word to read ) { read a character push the character on the stack } while ( the stack is not empty ) { write the stack's top character to the screen pop a character off the stack } 7. What is written to the screen for the input \"carpets\"? o A. serc o B. carpets o C. steprac o D. ccaarrppeettss 8. Here is an INCORRECT pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced: declare a character stack while ( more input is available) { read a character if ( the character is a '(' ) push it on the stack else if ( the character is a ')' and the stack is not empty ) pop a character off the stack else print \"unbalanced\" and exit } print \"balanced\" 9. Which of these unbalanced sequences does the above code think is balanced? o A. ((()) o B. ())(() o C. (()())) o D. (()))() 10. Consider the usual algorithm for determining whether a sequence of parentheses is balanced. What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))? o A. 1 o B. 2"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 12, "text": "B. ())(() o C. (()())) o D. (()))() 10. Consider the usual algorithm for determining whether a sequence of parentheses is balanced. What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))? o A. 1 o B. 2 o C. 3 o D. 4 o E. 5 or more Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 28 11. Consider the usual algorithm for determining whether a sequence of parentheses is balanced. Suppose that you run the algorithm on a sequence that contains 2 left parentheses and 3 right parentheses (in some order). What is the maximum number of parentheses that will ever appear on the stack AT ONE TIME during the computation? o A. 1 o B. 2 o C. 3 o D. 4 o E. 5 or more 12. Suppose we have an array implementation of the stack class, with ten items in the stack stored at data[0] through data[9]. The CAPACITY is 42. Where does the push member function place the new entry in the array? o A. data[0] o B. data[1] o C. data[9] o D. data[10] 13. Consider the implementation of the stack using a partially-filled array. What goes wrong if we try to store the top of the stack at location [0] and the bottom of the stack at the last used position of the array? o A. Both peek and pop would require linear time. o B. Both push and pop would require linear time. o C. The stack could not be used to check balanced parentheses. o D. The stack could not be used to evaluate postfix expressions. 14. In the linked list implementation of the stack class, where does the push member function place the new entry on the linked list? o A. At the head o B. At the tail o C. After all other entries that are greater than the new entry. o D. After all other entries that are smaller than the new entry. 15. In the array version of the stack class (with a fixed-sized array), which operations require linear time for their worst-case behavior? o A. is_empty o B. peek o C. pop o D. push o E. None of these operations require linear time. 16. In the linked-list version of the stack class, which operations require linear time for their worst-case behavior? o A. is_empty o B. peek o C. pop o D. push o E. None of these operations require linear time. Multiple Choice Section 7.3 Implementations of the stack ADT Multiple Choice Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 29 17. What is the value of the postfix expression 6 3 2 4 + - *: o A. Something between -15 and -100 o B. Something between -5 and -15 o C. Something between 5 and -5 o D. Something between 5 and 15 o E. Something between 15 and"} {"pdf_name": "DS-Module II-GangaHoli.pdf", "chunk_id": 13, "text": "17. What is the value of the postfix expression 6 3 2 4 + - *: o A. Something between -15 and -100 o B. Something between -5 and -15 o C. Something between 5 and -5 o D. Something between 5 and 15 o E. Something between 15 and 100 18. Here is an infix expression: 4+3*(6*3-12). Suppose that we are using the usual stack algorithm to convert the expression from infix to postfix notation. What is the maximum number of symbols that will appear on the stack AT ONE TIME during the conversion of this expression? o A. 1 o B. 2 o C. 3 o D. 4 o E. 5 Section 7.4 More Complex Stack Applications"} {"pdf_name": "DSA Mod2@AzDOCUMENTS.in-1.pdf", "chunk_id": 0, "text": "Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner Scanned by CamScanner"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 0, "text": "Data Structure & Applications Module III Notes Dr. Ganga Holi, Professor & Head, Department of Information Science & Engineering GLOBAL ACADEMY OF TECHNOLOGY Rajarajeshwari Nagar, Bangalore-560 098. Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 2 Table of Contents Table of Contents .................................................................................................................................... 2 1 Linked List Definition .................................................................................................................... 3 2 Representation of Linked List in Memory ............................................................................... 4 3 Memory Allocation and Deallocation ........................................................................................ 7 4 Linked List Operations .................................................................................................................. 8 1. Node creation .......................................................................................................................... 8 2. Insertion: .................................................................................................................................. 8 3. Deletion ..................................................................................................................................... 9 4. Traversing & Displaying ................................................................................................... 10 5 What is node? How it is created? ............................................................................................. 11 6 Write functions to insert the node at front and rear end. ............................................... 11 7 Write functions to delete node from front and rear end. .................................................. 12 8 Write functions to insert into ordered linked list ............................................................... 13 9 Write a function to delete a specified element. .................................................................... 14 10 Write a function to insert at specified position ............................................................... 15 11 Write a function to delete element from specified position ......................................... 16 12 Write a function to traverse the linked list and display alternative nodes. ........... 16 13 Write a function to reverse the linked list. ....................................................................... 17 14 Write a program to insert at front, rear, in ordered, at specified position, and delete from front, rear, ordered, element and from specified position. ............................... 20 15 Write a program to insert, delete from both ends and insert & delete from Ordered using circular single linked list. ...................................................................................... 25 16 Write a program to insert and delete from circular single linked list with head node. 31 17 Write a program to insert & delete from both ends with first & last pointer. ....... 38 18 Write a progrm to insert, delete from both ends and insert into ordered DLL and delete from Ordered DLL. ................................................................................................................... 42 19 Write a program to insert, delete from both ends and insert into ordered DLL and delete from Ordered DLL with header node, and last pointer. ...................................... 46 20 Write a program to create linked to represent polynomial equation and evaluate the equation with one variable(x7 + 8x \u2013 43). .............................................................................. 50 21 Write a program to create linked to represent polynomial equation and add two polynomial the equation with one variable P1: 2x7 + 83x +4x+5 & p2: 4x7 +5x2+18x +3. 53 Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 3 1 Linked List Definition List is a linear collection of data items. List can be implemented using arrays and linked lists. In arrays there is linear relationship between the data elements which is evident from the physical relationship of data in the memory. The address of any element in the array can easily be computed but, it is very difficult to insert and delete any element in an array. Usually, a large block of memory is occupied by an array which may"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 1, "text": "is evident from the physical relationship of data in the memory. The address of any element in the array can easily be computed but, it is very difficult to insert and delete any element in an array. Usually, a large block of memory is occupied by an array which may not be in use and it is difficult to increase the size of an array, if required. Another way of storing a list is to have each element in a list contain a field called a link or pointer, which contains the address of the address of the next element in the list. The successive elements in the list need not occupy adjacent space in memory. This type of data structure is called linked list. Linked List is a linear data structure and it is very common data structure which consists of group of nodes in a sequence which is divided in two parts. Each node consists of its own data and the address of the next node and forms a chain. Linked Lists are used to create trees and graphs. 1.1.1.1 Advantages of Linked Lists \u2022 They are a dynamic in nature which allocates the memory when required. \u2022 Insertion and deletion operations can be easily implemented. \u2022 Stacks and queues can be easily executed. \u2022 Linked List reduces the access time. 1.1.1.2 Disadvantages of Linked Lists \u2022 The memory is wasted as pointers require extra memory for storage. \u2022 No element can be accessed randomly; it has to access each node sequentially. \u2022 Reverse Traversing is difficult in single linked list. 1.1.1.3 Applications of Linked Lists \u2022 Linked lists are used to implement stacks, queues, graphs, etc. \u2022 Linked lists let you insert elements at the beginning and end of the list. \u2022 In Linked Lists we don\u2019t need to know the size in advance. 1.1.1.4 Types of Linked Lists \u2022 Singly Linked List : Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which points to the next node in sequence of nodes. The operations we can perform on singly linked lists are insertion, deletion and traversal. Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 4 \u2022 Doubly Linked List : In a doubly linked list, each node contains two links the first link points to the previous node and the next link points to the next node in the sequence. \u2022 Circular Linked List: In the circular linked list the last node of the list contains the address of the first node and forms a circular chain. 2 Representation of Linked List in Memory List can be represented using arrays and linked list. Array Representation: Linked list can be implemented using arrays. One array will be used for storing the information field and another array is used for storing the links. START variable will hold the beginning node address and INFO[9] has value and LINK[9] has the"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 2, "text": "represented using arrays and linked list. Array Representation: Linked list can be implemented using arrays. One array will be used for storing the information field and another array is used for storing the links. START variable will hold the beginning node address and INFO[9] has value and LINK[9] has the address of another node. Here LINK[9]=3 LINK[3]=6 LINK[6]=11 LINk[11]=7 LINK[7]]=10 LINK[10]=4 Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 5 LINKJ[4]=0 which is the last node in the linked list Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 6 Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 7 3 Memory Allocation and Deallocation Memory cane be allocated on heap if linked list is used and free function is used to deallocate the memory. Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 8 4 Linked List Operations 1. Node creation A linked-list is a sequence of nodes which are connected together via links. Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list the second most used data structure after array. Following are important terms to understand the concepts of Linked List. \u2022 INFO/Link \u2212 Each Link of a linked list can store a data called an element. \u2022 Next/Ptr \u2212 Each Link of a linked list contain a link to next link called Next. \u2022 LinkedList \u2212 A LinkedList contains the connection link to the first Link called First. As per above shown illustration, following are the important points to be considered. \u2022 Linked List contains a pointer variable called first. \u2022 Each node carries a data field(s) and a pointer Field called next. \u2022 Each node is linked with its next pointer using its next pointer. \u2022 Last node carries a pointer as null to mark the end of the list. Node can be created by using malloc function sturct node { int data; struct node *next; }; typedef struct node NODE; NODE *first=NULL; NODE *temp; Temp=(NODE*)malloc(siezof(NODE)); 2. Insertion: Insertion of node can be done in various ways. 1. Insertion at front. 2. Insert at rear end 3. Insert into ordered list 4. Insert at specified position. Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 9 void addrear(int data) { NODE *temp,*cur; temp=(NODE*)malloc(sizeof(NODE)); temp->data=data; temp->next=NULL; if(first==NULL) temp=first; return; cur=first; while(cur->next != NULL) { cur=cur->next; } cur->next =temp; return ; } void addfront(int data) { NODE *temp; temp=(NODE*)malloc(sizeof(NODE)); temp->data=data; temp->next=NULL: if (first== NULL) first=temp; else { temp->next=first; first=temp; } return ; } 3. Deletion Deletion of node can be done in various ways. 1. Deletion at from. 2. Deletion at rear end. 3. Deletion into ordered list 4. Deletion at specified position. void deletefront() { NODE *temp; int num; temp=first;"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 3, "text": "if (first== NULL) first=temp; else { temp->next=first; first=temp; } return ; } 3. Deletion Deletion of node can be done in various ways. 1. Deletion at from. 2. Deletion at rear end. 3. Deletion into ordered list 4. Deletion at specified position. void deletefront() { NODE *temp; int num; temp=first; if(first==NULL) { printf(\"List is Empty\"); return; } printf(\u201cdeleted element is %d\\n\u201d, first->data); first=first->next; free(temp); return ; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 10 } void deleterear() { NODE *cur, *prev; cur=first; prev=NULL; if(first==NULL) { printf(\"List is Empty\"); return; } if(first->next==NULL) { first=NULL; free(cur); return; } while(cur->next!=NULL) { prev=cur; cur=cur->next; } prev->next=NULL; free(cur); return; } 4. Traversing & Displaying void display() { NODE *r; r=first; printf(\"Data \\n\"); if(r==NULL) return; while(r!=NULL) { printf(\u201c%d\u2192\u201d, r->data); r=r->next; } } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 11 What is node? How it is created? #include #include struct node { int item; struct node *next; }; typedef struct node NODE; NODE *first=NULL; Node is created by calling malloc function and storing the return value in pointer to node variable. 5 Write functions to insert the node at front and rear end. struct node { int item; struct node *next; }; typedef struct node NODE; NODE* insertfront(NODE* first, int data) { NODE* temp; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return NULL; } temp\u2192item=data; temp\u2192next=NULL; if(first==NULL) first=temp; else { temp\u2192next=first; first=temp; } return first; } NODE* insertrear(NODE* first, int data) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 12 { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return NULL; } temp\u2192item=data; temp\u2192next=NULL; if(first==NULL) first=temp; else { cur=first; while(cur\u2192next!=NULL) { cur=cur\u2192next; } cur\u2192next=temp; } return first; } void display(NODE* first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return; } cur=first; while(cur!=NULL) { printf(\"%d\u2192\", cur\u2192item); cur=cur\u2192next; } printf(\"NULL\"); } 6 Write functions to delete node from front and rear end. NODE* deletefront(NODE* first) { NODE *temp; temp=first; if(first==NULL) { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 13 printf(\"List is Empty\"); return first; } printf(\"Front element deleted =%d\\n\",first\u2192item); first=first\u2192next; free(temp); return first; } NODE* deleterear(NODE* first) { NODE *cur, *prev; cur=first; if(first==NULL) { printf(\"List is Empty\"); return first; } if(first\u2192next==NULL) { printf(\"Deleted *** rear element=%d\\n\",first\u2192item); first=NULL; free(cur); return first; } prev=NULL; while(cur\u2192next!=NULL) { prev=cur; cur=cur\u2192next; } prev\u2192next=cur\u2192next; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return first; } 7 Write functions to insert into ordered linked list NODE* orderedInsert(NODE* first, int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; if(first==NULL) { first=nn; return first; } if(first\u2192item >ele) { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 14 nn\u2192next=first; first=nn; return first; } pre=first; cur=first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; } return first; } 8 Write"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 4, "text": "Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 14 nn\u2192next=first; first=nn; return first; } pre=first; cur=first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; } return first; } 8 Write a function to delete a specified element. NODE* deleteFromordered(NODE* first, int ele) { NODE *pre, *cur; if(first==NULL) { printf(\"Empty list\\n\"); return first; } cur=first; if(first\u2192item ==ele) { first=NULL; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return first; } pre=first; cur=first; while(cur\u2192item !=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur-->item !=ele && cur-->next ==NULL) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 15 { printf(\"Element not found\\n\"); return first; } pre\u2192next=cur\u2192next; } return first; } 9 Write a function to insert at specified position NODE* InsertAtPos(NODE* first, int ele, int pos) { NODE *nn, *pre, *cur; int count=1; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; if(first==NULL) { first=nn; return first; } if(pos==1) { nn\u2192next=first; first=nn; return first; } pre=first; cur=first; while(count < pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count >= pos) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; } return first; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 16 10 Write a function to delete element from specified position NODE* DeleteFromPos(NODE* first, int pos) { NODE *pre, *cur; int count=1; pre=NULL; cur=first; if(first==NULL) { printf(\"List is Empty\"); return first; } if(pos==1) { printf(\"Front element deleted =%d\\n\",first\u2192item); first=first\u2192next; free(cur); return first; } pre=first; cur=first; while(count != pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count!=pos && cur-->next==NULL) { printf(\" position is not found\\n\"); } if(count == pos) { pre\u2192next=cur\u2192next; printf(\"Element deleted %d from pos %d\\n\",pos, first\u2192item); free(cur); } return first; } 11 Write a function to traverse the linked list and display alternative nodes. void displayalt() { NODE *temp; temp=first; if(first==NULL) { printf(\"empty list\\n\"); return; } while(temp!=NULL) { printf(\"%d\u2192\",temp\u2192item); Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 17 if(temp\u2192next==NULL) break; temp=temp\u2192next\u2192next; } printf(\"\\ndone\\n\"); } int main() { int i,ele; printf(\"enter 4 elements=\"); for(i=0;i<5;i++) { printf(\"enter ele=\"); scanf(\"%d\",&ele); orderedInsert(ele); display(); } printf(\" Display alternate elements\\n\"); displayalt(); } 12 Write a function to reverse the linked list. #include #include struct node { int item; struct node *next; }; typedef struct node NODE; NODE *first=NULL; NODE *revFirst=NULL; NODE *newfirst=NULL; void orderedInsert(int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn-->next=NULL; if(first==NULL) { first=nn; return; } if(first\u2192item >ele) { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 18 nn\u2192next=first; first=nn; return; } pre=first; cur=first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; } } void display(NODE *first) { NODE *temp; temp=first; if(first==NULL) { printf(\"empty list\\n\"); return; } while(temp!=NULL) { printf(\"%d\u2192\",temp\u2192item); temp=temp\u2192next; } printf(\"\\ndone\\n\"); } NODE* insertFront(NODE *revFirst,int item) { NODE *nn; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=item; nn\u2192next=NULL; if(revFirst==NULL) revFirst=nn;"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 5, "text": "&& cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; } } void display(NODE *first) { NODE *temp; temp=first; if(first==NULL) { printf(\"empty list\\n\"); return; } while(temp!=NULL) { printf(\"%d\u2192\",temp\u2192item); temp=temp\u2192next; } printf(\"\\ndone\\n\"); } NODE* insertFront(NODE *revFirst,int item) { NODE *nn; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=item; nn\u2192next=NULL; if(revFirst==NULL) revFirst=nn; else { nn\u2192next=revFirst; revFirst=nn; } return revFirst; } void reverse1() Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 19 { struct node *nn,*prev = NULL; struct node *current = first; while (current!= NULL) { revFirst=insertFront(revFirst,current\u2192item); prev = current; current = current\u2192next; } } NODE* reverse2() { struct node* prev = NULL; struct node* current = first; struct node* next; while (current != NULL) { next = current\u2192next; current\u2192next = prev; prev = current; current = next; } newfirst = prev; } int main() { int i,ele,n; printf(\"enter n=\"); scanf(\"%d\",&n); printf(\"enter %d elements=\",n); for(i=0;i #include struct node { int item; struct node *next; }; typedef struct node NODE; NODE *head=NULL; void insertfront(int data) { NODE* temp; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return ; } temp\u2192item=data; temp\u2192next=NULL; if(head\u2192next==NULL) { head\u2192next=temp; head\u2192item++; } else { temp\u2192next=head\u2192next; head\u2192next=temp; head\u2192item++; } return; } void insertrear(int data) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 21 if(temp==NULL) { printf(\"insufficient memory\\n\"); return ; } temp-->item=data; temp\u2192next=NULL; if(head\u2192next==NULL) { head\u2192next=temp; } else { cur=head\u2192next; while(cur\u2192next!=NULL) { cur=cur\u2192next; } cur\u2192next=temp; } head\u2192item++; return ; } void deletefront() { NODE *temp; int num; temp=head\u2192next; if(head\u2192next==NULL) { printf(\"List is Empty\"); return; } printf(\"Front element deleted =%d\\n\",temp-->item); head\u2192next=temp\u2192next; head\u2192item--; free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=head\u2192next; if(head\u2192next==NULL) { printf(\"List is Empty\"); return; } if(cur\u2192next==NULL) { printf(\"Deleted *** rear element=%d\\n\",cur\u2192item); head\u2192next=NULL; head\u2192item--; free(cur); return ; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 22 prev=NULL; while(cur\u2192next!=NULL) { prev=cur; cur=cur\u2192next; } prev\u2192next=cur\u2192next; head\u2192item--; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return ; } void orderedInsert(int ele) { NODE *nn, *pre, *cur, *first; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; first=head\u2192next; if(first==NULL) { head\u2192next=nn; head\u2192item++; return; } if(first\u2192item >ele) { nn\u2192next=first; head\u2192next=nn; head\u2192item++; return; } pre=first; cur=first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; head\u2192item++; } else { cur\u2192next=nn; head\u2192item++; } } void deleteFromordered(int ele) { NODE *pre, *cur; if(head-->next==NULL) { printf(\"Empty list\\n\"); return ; } cur=head\u2192next; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 23 if(cur\u2192item ==ele)"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 6, "text": "} if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; head\u2192item++; } else { cur\u2192next=nn; head\u2192item++; } } void deleteFromordered(int ele) { NODE *pre, *cur; if(head-->next==NULL) { printf(\"Empty list\\n\"); return ; } cur=head\u2192next; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 23 if(cur\u2192item ==ele) { head\u2192next=NULL; head\u2192item--; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return ; } pre=NULL; while(cur\u2192item !=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item !=ele && cur\u2192next ==NULL) { printf(\" Element not found\\n\"); return; } if(cur\u2192item == ele) { pre\u2192next=cur\u2192next; head\u2192item--; } return ; } void InsertAtPos(int ele, int pos) { NODE *nn, *pre, *cur; int count=1; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; if(head\u2192next==NULL) { head\u2192next=nn; head\u2192item++; return; } if(pos==1) { nn\u2192next=head\u2192next; head\u2192next=nn; head\u2192item++; return; } pre=NULL; cur=head\u2192next; while(count < pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count >= pos) { pre\u2192next=nn; nn\u2192next=cur; } else { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 24 cur\u2192next=nn; } head\u2192item++; return ; } void DeleteFromPos(int pos) { NODE *pre, *cur; int count=1; pre=NULL; cur=head-->next; if(head\u2192next==NULL) { printf(\"List is Empty\"); return ; } if(pos==1) { printf(\"Front element deleted =%d\\n\",cur-->item); head\u2192next=cur\u2192next; head\u2192item--; free(cur); return ; } pre=NULL; cur=head\u2192next; while(count != pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count != pos && cur\u2192next ==NULL) { printf(\"Posotion not valid\\n\"); return; } if(count == pos) { pre\u2192next=cur\u2192next; head-->item--; printf(\"Element deleted %d from pos %d\\n\",pos, cur\u2192item); free(cur); } return ; } void display() { NODE *temp, *first; temp=first=head\u2192next;; if(first==NULL) { printf(\"empty list\\n\"); return; } while(temp!=NULL) { printf(\"%d\u2192\",temp\u2192item); temp=temp\u2192next; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 25 } printf(\"\\ndone total nodes=%d\\n\", head\u2192item); } int main() { int i,ele, val, pos; head=(NODE*) malloc(sizeof(NODE)); head\u2192next=NULL; head-->item=0; printf(\"enter 4 elements=\"); for(i=0;i<4;i++) { printf(\"enter ele=\"); scanf(\"%d\",&val); insertfront(val); //orderedInsert(val); display(); } printf(\"\\n item value and position=\"); scanf(\"%d%d\", &val,&pos); InsertAtPos(val,pos); display(); printf(\"\\n Enter value to delete =\"); scanf(\"%d\", &val); deleteFromordered(val); display(); printf(\"\\n Enter posotion from which ele to delete =\"); scanf(\"%d\", &pos); DeleteFromPos(pos); display(); } 14 Write a program to insert, delete from both ends and insert & delete from Ordered using circular single linked list. #include #include struct node { int item; struct node *next; }; typedef struct node NODE; NODE* insertfront(NODE* first, int data) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 26 { NODE* temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return NULL; } Temp\u2192item=data; Temp\u2192next=NULL; if(first==NULL) { first=temp; first\u2192next=first; } else { cur=first; while(cur\u2192next!=first) { cur=cur\u2192next; } temp\u2192next=first; first=temp; cur\u2192next=first; } return first; } NODE* insertrear(NODE* first, int data) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return NULL; } temp\u2192item=data; temp\u2192next=NULL; if(first==NULL) { first=temp; first\u2192next=first; } else { cur=first; while(cur\u2192next!=first) { cur=cur\u2192next; } cur\u2192next=temp; temp\u2192next=first; } return first; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 27 void display(NODE* first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return;"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 7, "text": "temp\u2192next=NULL; if(first==NULL) { first=temp; first\u2192next=first; } else { cur=first; while(cur\u2192next!=first) { cur=cur\u2192next; } cur\u2192next=temp; temp\u2192next=first; } return first; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 27 void display(NODE* first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return; } cur=first; while(cur-->next!=first) { printf(\"%d-\u2192\", cur\u2192item); cur=cur\u2192next; } printf(\"%d-\u2192\", cur\u2192item); printf(\"NULL\\n\\n\"); } NODE* deletefront(NODE* first) { NODE *temp, *last; int num; temp=first; if(first==NULL) { printf(\"List is Empty\"); return first; } printf(\"Front element deleted =%d\\n\",first\u2192item); last=first; while(last\u2192next!=first) { last=last\u2192next; } first=first\u2192next; last\u2192next=first; free(temp); return first; } NODE* deleterear(NODE* first) { NODE *cur, *prev; cur=first; if(first==NULL) { printf(\"List is Empty\"); return first; } if(first\u2192next==NULL) { printf(\"Deleted *** rear element=%d\\n\",first\u2192item); first=NULL; free(cur); return first; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 28 } prev=NULL; while(cur\u2192next!=first) { prev=cur; cur=cur\u2192next; } prev\u2192next=cur\u2192next; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return first; } NODE* orderedInsert(NODE* first, int ele) { NODE *nn, *pre, *cur, *last; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; if(first==NULL) { first=nn; first\u2192next=first; first; } if(first\u2192item >ele) { nn\u2192next=first; last=first; while(last\u2192next!=first) { last=last\u2192next; } first=nn; last\u2192next=first; return first; } pre=first; cur=first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; nn\u2192next=first; } return first; } NODE* deleteFromordered(NODE* first, int ele) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 29 { NODE *pre, *cur,*last; if(first==NULL) { printf(\"Empty list\\n\"); return first; } cur=first; if(first\u2192item ==ele) { first=first\u2192next; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); last=first; while(last\u2192next!=first) { last=last\u2192next; } last\u2192next=first; free(cur); return first; } pre=first; cur=first; while(cur\u2192item !=ele && cur\u2192next !=first) { pre=cur; cur=cur\u2192next; } if(cur\u2192item !=ele && cur\u2192next ==first) { printf(\"Element not found\\n\"); return first; } pre\u2192next=cur\u2192next; free(cur); return first; } NODE* InsertAtPos(NODE* first, int ele, int pos) { NODE *nn, *pre, *cur, *last; int count=1; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; if(first==NULL) { first=nn; first\u2192next=first; return first; } if(pos==1) { nn\u2192next=first; last=first; while(last\u2192next!=first) { last=last\u2192next; } first=nn; last\u2192next=first; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 30 return first; } pre=NULL; cur=first; while(count < pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count >= pos) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; nn\u2192next=first; } return first; } NODE* DeleteFromPos(NODE* first, int pos) { NODE *nn, *pre, *cur, *last; int count=1; pre=NULL; cur=first; if(first==NULL) { printf(\"List is Empty\"); return first; } if(pos==1) { printf(\"Front element deleted =%d\\n\",first\u2192item); last=first; while(last\u2192next!=first) { last=last\u2192next; } first=first\u2192next; last\u2192next=first; free(cur); return first; ; } pre=NULL; cur=first; while(count != pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count!=pos && cur\u2192next==NULL) { printf(\" position is not found\\n\"); } if(count == pos) { pre\u2192next=cur\u2192next; printf(\"Element deleted %d from pos %d\\n\",pos, first\u2192item); free(cur); Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 31 } return first; } int main() { int val, n,i,pos; NODE *first=NULL; printf(\" Enter n of nodes n=\"); scanf(\"%d\", &n); for(i=0;i #include Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 32 struct node { int item; struct node *next; }; typedef struct node NODE; NODE *head=NULL; void insertfront(int data) { NODE* temp, *last; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return ; } temp\u2192item=data; temp\u2192next=NULL; if(head\u2192next==NULL) { printf(\" First element\\n\\n\"); head\u2192next=temp; temp\u2192next=temp; head\u2192item++; } else { temp\u2192next=head\u2192next; last=head\u2192next; while(last\u2192next!=head\u2192next) { last=last\u2192next; } head\u2192next=temp; last\u2192next=head\u2192next; head\u2192item++; } return; } void insertrear(int data) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return ; } temp\u2192item=data; temp\u2192next=NULL; if(head\u2192next==NULL) { head\u2192next=temp; temp\u2192next=temp; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 33 } else { cur=head\u2192next; while(cur\u2192next!=head\u2192next) { cur=cur\u2192next; } cur\u2192next=temp; temp\u2192next=head\u2192next; } head\u2192item++; return ; } void deletefront() { NODE *temp, *last; int num; temp=head-->next; if(head\u2192next==NULL) { printf(\"List is Empty\"); return; } printf(\"Front element deleted =%d\\n\",temp\u2192item); last=head\u2192next; while(last\u2192next!=head\u2192next) { last=last\u2192next; } head\u2192next=temp\u2192next; last\u2192next=head\u2192next; head-->item--; free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=head-->next; if(head-->next==NULL) { printf(\"List is Empty\"); return; } if(cur\u2192next==NULL) { printf(\"Deleted *** rear element=%d\\n\",cur\u2192item); head\u2192next=NULL; head\u2192item--; free(cur); return ; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 34 prev=NULL; while(cur\u2192next!=NULL) { prev=cur; cur=cur\u2192next; } prev\u2192next=cur\u2192next; head\u2192item--; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return ; } void orderedInsert(int ele) { NODE *nn, *pre, *cur, *last; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; cur=head\u2192next; if(head\u2192next==NULL) { head\u2192next=nn; nn\u2192next=nn; head\u2192item++; return; } if(cur\u2192item >ele) { nn\u2192next=cur; last=cur; while(last\u2192next!=head-->next) { last=last\u2192next; } head\u2192next=nn; last\u2192next=head\u2192next; head\u2192item++; return; } pre=NULL; cur=head\u2192next; while(cur\u2192item <=ele && cur\u2192next !=head\u2192next) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; head\u2192item++; } else { cur\u2192next=nn; nn\u2192next=head\u2192next; head\u2192item++; } } void deleteFromordered(int ele) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 35 { NODE *pre, *cur, *last; if(head\u2192next==NULL) { printf(\"Empty list\\n\"); return ; } cur=head\u2192next; if(cur\u2192item ==ele) { if(cur\u2192next==head\u2192next) { head\u2192next=NULL; } else { last=head\u2192next; while(last\u2192next!=head\u2192next) { last=last\u2192next; } head\u2192next=cur\u2192next; last\u2192next=head\u2192next; } printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); head\u2192item--; return ; } pre=NULL; while(cur\u2192item !=ele && cur\u2192next !=head\u2192next) { pre=cur; cur=cur\u2192next; } if(cur\u2192item !=ele && cur\u2192next ==NULL) { printf(\" Element not found\\n\"); return; } if(cur\u2192item == ele) { pre\u2192next=cur\u2192next; free(cur); head\u2192item--; } return ; } void InsertAtPos(int ele, int"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 9, "text": "last=last\u2192next; } head\u2192next=cur\u2192next; last\u2192next=head\u2192next; } printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); head\u2192item--; return ; } pre=NULL; while(cur\u2192item !=ele && cur\u2192next !=head\u2192next) { pre=cur; cur=cur\u2192next; } if(cur\u2192item !=ele && cur\u2192next ==NULL) { printf(\" Element not found\\n\"); return; } if(cur\u2192item == ele) { pre\u2192next=cur\u2192next; free(cur); head\u2192item--; } return ; } void InsertAtPos(int ele, int pos) { NODE *nn, *pre, *cur, *last; int count=1; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; if(head\u2192next==NULL) { head\u2192next=nn; nn\u2192next=nn; head\u2192item++; return; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 36 if(pos==1) { nn\u2192next=head\u2192next; last=head\u2192next; while(last\u2192next!=head\u2192next) { last=last\u2192next; } head\u2192next=nn; last\u2192next=head\u2192next; head\u2192item++; return; } pre=NULL; cur=head\u2192next; while(count < pos && cur\u2192next !=head\u2192next) { pre=cur; count++; cur=cur\u2192next; } if(count >= pos) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; nn\u2192next=head\u2192next; } head\u2192item++; return ; } void DeleteFromPos(int pos) { NODE *pre, *cur, *last; int count=1; pre=NULL; cur=head\u2192next; if(head\u2192next==NULL) { printf(\"List is Empty\"); return ; } if(pos==1) { printf(\"Front element deleted =%d\\n\",cur\u2192item); last=head\u2192next; while(last\u2192next!=head\u2192next) { last=last\u2192next; } head\u2192next=cur\u2192next; last\u2192next=head\u2192next; head\u2192item--; free(cur); return ; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 37 } pre=NULL; cur=head\u2192next; while(count != pos && cur\u2192next !=NULL) { pre=cur; count++; cur=cur\u2192next; } if(count != pos && cur\u2192next ==NULL) { printf(\"Posotion not valid\\n\"); return; } if(count == pos) { pre\u2192next=cur\u2192next; head\u2192item--; printf(\"Element deleted %d from pos %d\\n\",pos, cur\u2192item); free(cur); } return ; } void display() { NODE *temp; temp=head\u2192next; if(head\u2192next==NULL) { printf(\"empty list\\n\"); return; } while(temp\u2192next!=head\u2192next) { printf(\"%d\u2192\",temp\u2192item); temp=temp\u2192next; } printf(\"%d\u2192\",temp\u2192item); printf(\"\\n \\nDone total nodes=%d\\n\", head\u2192item); } int main() { int i,ele, val, pos,n; head=(NODE*) malloc(sizeof(NODE)); head\u2192next=NULL; head\u2192item=0; printf(\"enter n=\"); scanf(\"%d\",&n); printf(\"enter %d elements=\",n); for(i=0;i #include struct node { int item; struct node *next; }; typedef struct node NODE; void insertfront(NODE** first, NODE **last, int data) { NODE* temp; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return ; } Temp\u2192item=data; Temp\u2192next=NULL; if(*first==NULL) { *first=temp; *last=temp; } else { temp\u2192next=*first; *first=temp; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 39 } return; } void insertrear(NODE** first, NODE **last, int data) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return ; } temp\u2192item=data; temp\u2192next=NULL; if(*first==NULL) { *first=temp; *last=temp; } else { cur=*last; cur\u2192next=temp; *last=temp; } return ; } void display(NODE* first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return; } cur=first; while(cur!=NULL) { printf(\"%d\u2192\", cur->item); cur=cur\u2192next; } printf(\"NULL\\n\\n\"); } void deletefront(NODE** first, NODE **last) { NODE *temp; int num; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 10, "text": "void display(NODE* first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return; } cur=first; while(cur!=NULL) { printf(\"%d\u2192\", cur->item); cur=cur\u2192next; } printf(\"NULL\\n\\n\"); } void deletefront(NODE** first, NODE **last) { NODE *temp; int num; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 40 temp=*first; if(*first==NULL) { printf(\"List is Empty\"); return ; } printf(\"Front element deleted =%d\\n\",temp\u2192item); *first=temp\u2192next; free(temp); return ; } NODE* deleterear(NODE** first, NODE **last) { NODE *cur, *prev; cur=*first; if(*first==NULL) { printf(\"List is Empty\"); return; } if(cur\u2192:next==NULL) { printf(\"Deleted *** rear element=%d\\n\",cur\u2192item); *first=NULL; free(cur); return ; } prev=NULL; while(cur\u2192next!=NULL) { prev=cur; cur=cur\u2192next; } Prev\u2192next=cur\u2192next; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return; } NODE* orderedInsert(NODE** first, NODE **last, int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; cur=*first; if(*first==NULL) { *first=nn; return ; } if(cur\u2192item >ele) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 41 { nn\u2192next=*first; *first=nn; return ; } pre=NULL; cur=*first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192next=cur; } else { cur\u2192next=nn; } return ; } int main() { int val, n,i,pos; NODE *first=NULL, *last=NULL; printf(\" Enter n of nodes n=\"); scanf(\"%d\", &n); for(i=0;i #include #include struct node { int item; struct node *next; struct node *prev; }; typedef struct node NODE; NODE *first=NULL; void insertrear(int ele) { NODE *temp,*cur, *prev; temp= (NODE *)malloc(sizeof(NODE)); temp\u2192item=ele; temp\u2192next=NULL; if(first==NULL) { first=temp; return; } cur=first; prev=NULL; while(cur\u2192next != NULL) { prev=cur; cur=cur\u2192next; } cur\u2192next =temp; tem\u2192prev=prev; return ; } void insertfront(int ele) { NODE *temp; temp= (NODE *)malloc(sizeof(NODE)); temp\u2192item=ele; temp\u2192next=NULL; if (first== NULL) { first=temp; } else { temp\u2192next=first; first\u2192prev=temp; first=temp; } return ; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 43 void deletefront() { NODE *temp; int num; temp=first; if(first==NULL) { printf(\" List is Empty \\n\");return ; } if(first\u2192next==NULL) first=NULL; else { first=first\u2192next; First\u2192prev=NULL; } printf(\" Element=%d\\n\", temp\u2192item); free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=first; prev=NULL; if(first==NULL) { printf(\" List is Empty \\n\");return ; } if(first\u2192next==NULL) { first=NULL; } else { while(cur\u2192next!=NULL) { prev=cur; cur=cur\u2192next; } prev\u2192next=NULL; } printf(\" Element=%d\\n\", cur\u2192item); free(cur); return; } void display() { NODE *r; int count=0; r=first; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 44 if(r==NULL) { return; } printf(\"Doubly Linked List\\n\"); while(r!=NULL) { printf(\"%d-\u2192\",r->item); r=r\u2192next; count++; } printf(\"\\n No. Of Nodes=%d\\n\",count); } void insertOrdered(int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; nn\u2192prev=NULL; if(first==NULL) { first=nn; return; } if(first\u2192item >ele) { nn\u2192next=first; first\u2192prev=nn; first=nn; return;"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 11, "text": "Head, ISE Dept., Global Academy of Technology 44 if(r==NULL) { return; } printf(\"Doubly Linked List\\n\"); while(r!=NULL) { printf(\"%d-\u2192\",r->item); r=r\u2192next; count++; } printf(\"\\n No. Of Nodes=%d\\n\",count); } void insertOrdered(int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn\u2192item=ele; nn\u2192next=NULL; nn\u2192prev=NULL; if(first==NULL) { first=nn; return; } if(first\u2192item >ele) { nn\u2192next=first; first\u2192prev=nn; first=nn; return; } pre=NULL; cur=first; while(cur\u2192item <=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item >ele) { pre\u2192next=nn; nn\u2192prev=pre; nn\u2192next=cur; cur\u2192prev=nn; } else { cur\u2192next=nn; nn\u2192prev=cur; } } void deleteOrdered(int ele) { NODE *pre, *cur; if(first==NULL) { printf(\"Empty list\\n\"); return first; } cur=first; if(first\u2192item ==ele) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 45 { first=first\u2192next; if(first!=NULL) first\u2192prev=NULL; printf(\"Deleted Rear element=%d\\n\",cur\u2192item); free(cur); return first; } pre=NULL; cur=first; while(cur\u2192item !=ele && cur\u2192next !=NULL) { pre=cur; cur=cur\u2192next; } if(cur\u2192item !=ele && cur\u2192next ==NULL) { printf(\"Element not found\\n\"); return first; } pre\u2192next=cur\u2192next; return ; } int main() { int ele; int i, ch; first=NULL; while(1) { printf(\"\\nList Operations\\n\"); printf(\"===============\\n\"); printf(\"1.Insert at Front end\\n\"); printf(\"2.Deletion from the Front end\\n\"); printf(\"3.Insertion at the Rear end of DLL\\n\"); printf(\"4.Deletion from the rear end End of DLL\"); printf(\"5.Display DLL\\n\"); printf(\"6.Perform Insertion into Ordered DLL\\n\"); printf(\"7.Deletion from the Ordered DLL\\n\"); printf(\"8.Exit\\n\"); printf(\"Enter your choice : \"); scanf(\"%d\",&i); switch(i) { case 1 : printf(\"Enter Item=\"); scanf(\"%d\",&ele); insertfront(ele); break; case 2 : deletefront(); break; case 3 : printf(\"Enter Item=\"); scanf(\"%d\",&ele); insertrear(ele); break; case 4 : deleterear(); break; case 5 : if(first==NULL) printf(\"List is Empty\\n\"); else display(); break; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 46 case 6 : printf(\"Enter Item=\"); scanf(\"%d\",&ele); insertOrdered(ele); break; case 7 : printf(\"Enter Item to delete=\"); scanf(\"%d\",&ele); deleteOrdered(ele); break; case 8 : return 0; default : printf(\"Invalid option\\n\"); } } return 0; } 18 Write a program to insert, delete from both ends and insert into ordered DLL and delete from Ordered DLL with header node, and last pointer. /* Doubly Linked List (DLL) with first and last pointer */ #include #include #include struct node { int item; struct node *next; struct node *prev; }; typedef struct node NODE; NODE *head=NULL, *last=NULL; void insertrear(int ele) { NODE *temp,*cur, *prev; temp= (NODE *)malloc(sizeof(NODE)); temp->item=ele; temp->next=NULL; temp->prev=NULL; if(head->next==NULL) { head->next=temp; last=temp;return; } last->next =temp; temp->prev=last; last=temp; return ; } void insertfront(int ele) { NODE *temp; temp= (NODE *)malloc(sizeof(NODE)); temp->item=ele; temp->next=NULL; temp->prev=NULL; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 47 if (head->next== NULL) { head->next=temp; last=temp; } else { temp->next=head->next; head->next->prev=temp; head->next=temp; } return ; } void deletefront() { NODE *temp; int num; temp=head->next; if(head->next==NULL) { printf(\" List is Empty \\n\");return ; } if(head->next==last) { head->next=last=NULL; } else { head->next=temp->next; temp->prev=NULL; } printf(\" Element=%d\\n\", temp->item); free(temp); return ; } void deleterear() { NODE *cur, *pre; cur=last; if(head->next==NULL) { printf(\" List is Empty \\n\");return ; } printf(\" Element=%d\\n\", last->item); if(head->next==last) { head->next=last=NULL; } else { pre=last->prev; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept.,"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 12, "text": "head->next=temp->next; temp->prev=NULL; } printf(\" Element=%d\\n\", temp->item); free(temp); return ; } void deleterear() { NODE *cur, *pre; cur=last; if(head->next==NULL) { printf(\" List is Empty \\n\");return ; } printf(\" Element=%d\\n\", last->item); if(head->next==last) { head->next=last=NULL; } else { pre=last->prev; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 48 pre->next=NULL; last=pre; } free(cur); return; } void display() { NODE *r; int count=0; r=head->next; if(r==NULL) { return; } printf(\"Doubly Linked List\\n\"); while(r!=NULL) { printf(\"%d-->\",r->item); r=r->next; count++; } printf(\"\\n No. Of Nodes=%d\\n\",count); } void insertOrdered(int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn->item=ele; nn->next=NULL; nn->prev=NULL; if(head->next==NULL) { head->next=last=nn; return; } if(head->next->item >ele) { nn->next=head->next; head->next->prev=nn; head->next=nn; return; } pre=NULL; cur=head->next; while(cur->item <=ele && cur->next !=NULL) { pre=cur; cur=cur->next; } if(cur->item >ele) { pre->next=nn; nn->prev=pre; nn->next=cur; cur->prev=nn; } else { cur->next=nn; nn->prev=cur; last=nn; } } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 49 void deleteOrdered(int ele) { NODE *pre, *cur; if(head->next==NULL) { printf(\"Empty list\\n\"); return; } cur=head->next; if(cur->item ==ele) { head->next=cur->next; if(head->next!=NULL) head->next->prev=NULL; printf(\"Deleted Rear element=%d\\n\",cur->item); free(cur); return ; } pre=NULL; cur=head->next; while(cur->item !=ele && cur->next !=NULL) { pre=cur; cur=cur->next; } if(cur->item !=ele && cur->next ==NULL) { printf(\"Element not found\\n\"); return ; } pre->next=cur->next; return ; } int main() { int ele; int i, ch; head= (NODE *)malloc(sizeof(NODE)); head->item=0; head->next=NULL; head->prev=NULL; while(1) { printf(\"\\nList Operations\\n\"); printf(\"===============\\n\"); printf(\"1.Insert at Front end\\n\"); printf(\"2.Deletion from the Front end\\n\"); printf(\"3.Insertion at the Rear end of DLL\\n\"); printf(\"4.Deletion from the rear end End of DLL\\n\"); printf(\"5.Display DLL\\n\"); printf(\"6.Perform Insertion into Ordered DLL\\n\"); printf(\"7.Deletion from the Ordered DLL\\n\"); printf(\"8.Exit\\n\"); printf(\"Enter your choice : \"); scanf(\"%d\",&i); Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 50 switch(i) { case 1 : printf(\"Enter Item=\"); scanf(\"%d\",&ele); insertfront(ele); break; case 2 : deletefront(); break; case 3 : printf(\"Enter Item=\"); scanf(\"%d\",&ele); insertrear(ele); break; case 4 : deleterear(); break; case 5 : if(head->next==NULL) printf(\"List is Empty\\n\"); else display(); break; case 6 : printf(\"Enter Item=\"); scanf(\"%d\",&ele); insertOrdered(ele); break; case 7 : printf(\"Enter Item to delete=\"); scanf(\"%d\",&ele); deleteOrdered(ele); break; case 8 : return 0; default : printf(\"Invalid option\\n\"); } } return 0; } 19 Write a program to create linked to represent polynomial equation and evaluate the equation with one variable(x7 + 8x \u2013 43). #include #include struct node { int coef, pwr; struct node *next; }; typedef struct node NODE; NODE* insertrear(NODE *first, int c, int p) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 51 { printf(\"insufficient memory\\n\"); return NULL; } temp->coef=c; temp->pwr=p; temp->next=NULL; if(first==NULL) first=temp; else { cur=first; while(cur->next!=NULL) { cur=cur->next; } cur->next=temp; } return first; } void display(NODE *first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return ; } cur=first; while(cur!=NULL) { printf(\"%dx^%d + \", cur->coef, cur->pwr); cur=cur->next; } printf(\"NULL\\n\\n\"); } void evaluate(NODE *third, int x) { NODE *cur; int s=0; cur=third; if(third==NULL) { printf(\" empty list\\n\"); return; } while(cur!=NULL)"} {"pdf_name": "DSA-Module-III Notes.pdf", "chunk_id": 13, "text": "cur->next=temp; } return first; } void display(NODE *first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return ; } cur=first; while(cur!=NULL) { printf(\"%dx^%d + \", cur->coef, cur->pwr); cur=cur->next; } printf(\"NULL\\n\\n\"); } void evaluate(NODE *third, int x) { NODE *cur; int s=0; cur=third; if(third==NULL) { printf(\" empty list\\n\"); return; } while(cur!=NULL) { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 52 s=s+cur->coef*pow(x, cur->pwr); cur=cur->next; } printf(\"Value=%d\\n\",s); return; } int main() { int c, p, x,ln1,ln2,i; NODE *first=NULL; NODE *second=NULL; NODE *third=NULL; printf(\" Enter no of nodes for first List=\"); scanf(\"%d\", &ln1); for(i=0;i #include struct node { int coef, pwr; struct node *next; }; typedef struct node NODE; NODE* insertrear(NODE *first, int c, int p) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf(\"insufficient memory\\n\"); return NULL; } temp->coef=c; temp->pwr=p; temp->next=NULL; if(first==NULL) first=temp; else { cur=first; while(cur->next!=NULL) { cur=cur->next; } cur->next=temp; } return first; } void display(NODE *first) { NODE *cur; if(first==NULL) { printf(\" Empty List\\n\"); return ; } cur=first; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 54 while(cur!=NULL) { printf(\"%dx^%d + \", cur->coef, cur->pwr); cur=cur->next; } printf(\"NULL\\n\\n\"); } NODE* polyadd(NODE *first, NODE *second, NODE *third) { NODE *nn, *cur1, *cur2; int sum; nn=(NODE*)malloc(sizeof(NODE)); cur1=first; cur2=second; if(cur1==NULL && cur2==NULL) return NULL; if(cur1==NULL) return cur2; if(cur2==NULL) return cur1; while(cur1!=NULL && cur2!=NULL) { if(cur1->pwr >cur2->pwr) { third=insertrear(third, cur1->coef, cur1->pwr); display(third); cur1=cur1->next; } else if(cur1->pwr==cur2->pwr) { sum=cur1->coef+cur2->coef; third=insertrear(third, sum, cur1->pwr); display(third); cur1=cur1->next;cur2=cur2->next; } else { third=insertrear(third, cur2->coef, cur2->pwr); display(third); cur2=cur2->next; } } if(cur1==NULL) { while(cur2!=NULL) { third=insertrear(third, cur2->coef, cur2->pwr); cur2=cur2->next; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 55 } else if(cur2==NULL) { while(cur1!=NULL) { third=insertrear(third, cur1->coef, cur1->pwr); cur1=cur1->next; } } return third; } int main() { int c, p, x,ln1,ln2,i; NODE *first=NULL; NODE *second=NULL; NODE *third=NULL; printf(\" Enter no of nodes for first List=\"); scanf(\"%d\", &ln1); for(i=0;i= K 3. Move Jth element downward Set[J+1] := A[J] 4. Decrease counter Set J := J-1 End of step 2 loop 5. Insert element Set A[K] := ITEM 6. Reset N Set N := N+1 7. Exit (iii) Deletion Deletion refers to the operation of removing an element from the array. Deleting the element from the end of an array is not a problem, but deleting from middle requires movement of each element upwards in order to fill up the void in the array. Algorithm for Deletion Let A be a linear array. The function used to delete from the array is DELETE(a, N, K, ITEM) where, N is the number of elements, K is the positive integer such that K<=N. The algorithm delets Kth element from the array. 1. Set ITEM := A[k] 2. Repeat for J - K to N-1 [Move J+1 element upward] Set A[J] := A[J+1] End of loop 3. Reset the number N of elements in A Set N := N-1 4. Exit 6. Describe the method to calculate the actual memory address of the array location. Address Calculation in One Dimension Array: Array of an element of an array say \u201cA[ I ]\u201d is calculated using the following formula: Address of A [ I ] = B + W * ( I \u2013 LB ) Where, B = Base address W = Storage Size of one element stored in the array (in byte) I = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero) Example: Given the base address of an array B[1300\u2026..1900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700]. Solution: The given values are: B = 1020, LB ="} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 3, "text": "Lower limit / Lower Bound of subscript, if not specified assume 0 (zero) Example: Given the base address of an array B[1300\u2026..1900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700]. Solution: The given values are: B = 1020, LB = 1300, W = 2, I = 1700 Address of A [ I ] = B + W * ( I \u2013 LB ) = 1020 + 2 * (1700 \u2013 1300) = 1020 + 2 * 400 = 1020 + 800 = 1820 [Ans] Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 4 Address Calculation in Two Dimensional Array: Address of A [I][j] = B + W *((i-LB)*(UB-LB+1)+ (j \u2013 LB )) Example: Hint: Formula for calculating address for multi dimensional arrays Li=upper bound-lower bound+1, where L is the number of elements in Column. For a given subscript Ki, the effective index Ei of Li is the number of indices preceding Ki in the index set and Ei can be calculated from Ei=Ki-lower bound Then the address LOC(K1, K2, K3\u2026...Kn) of an ordinary element of C array can be obtained from the formula Base(C )+w[(((\u2026(EnLn-1 +En-1 )Ln-2 + En-2 )Ln-3 + +E3)L2 + E2)L1 +E1) or from the formula Base( C )+ w[(\u2026((E1L2 +E2 )L3 + E3 )L4 + \u2026.+En-1)Ln+ En) While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. Therefore, a 2-D array must be linearized so as to enable their storage. There are two alternatives to achieve linearization: Row-Major and Column-Major. Address of an element of any array say \u201cA[ I ][ J ]\u201d is calculated in two forms as given: (1) Row Major System (2) Column Major System Row Major System: The address of a location in Row Major System is calculated using the following formula: Address of A [ I ][ J ] = B + W * [ N * ( I \u2013 Lr ) + ( J \u2013 Lc ) ] Column Major System: The address of a location in Column Major System is calculated using the following formula: Address of A [ I ][ J ] Column Major Wise = B + W * [( I \u2013 Lr ) + M * ( J \u2013 Lc )] Where, B = Base address I = Row subscript of element whose address is to be found J = Column subscript of element whose address is to be found W = Storage Size of one element stored in the array (in byte) Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero) Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero) M = Number of row of the given matrix N = Number of column of the given matrix 7. What are Polynomials and Sparse matrices? Explain with example. Polynomial is an expression consisting of variables and co-efficients which only employs operations"} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 4, "text": "index of matrix, if not given assume 0 (zero) M = Number of row of the given matrix N = Number of column of the given matrix 7. What are Polynomials and Sparse matrices? Explain with example. Polynomial is an expression consisting of variables and co-efficients which only employs operations of addition, subtraction and multiplication. Ex: x^2-4x+7 is a single variable equation. x^3+xyz^2+x^2y+z+10 is a 3 variable polynomial equation. The largest exponent (power) of a polynomial is called its degree. Co-efficients that are zero are not displayed. Program to evaluate polynomial Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 5 How to represent polynomial and Evaluate polynomials? // Evaluation of polynomial equation #include typedef struct { int coef,power; }term; term a[100]; int main() { int i, x, n,m, sum=0; i=0; printf(\"Enter n=\" ); scanf(\"%d\", &n); printf(\" Enter Polynomial Coef and power=\"); for(i=0;i typedef struct { int coef,power; }term; term a[100]; int startA, startB, finishA, finishB, avail, count=0; int compare(int a, int b) { if(a>b) return 1; else if(a=100) { fprintf(stdout, \"cannot add poly\\n\"); return ; } a[avail].coef=coef; a[avail].power=power; printf(\"added coef=%d \",a[avail].coef); avail++; count++; } void display() { int i=0, k; printf(\" Ist polynomial=\\n\"); for(;i<=finishA;i++) printf(\"%d %d\\n\",a[i].coef,a[i].power); printf(\" IIst polynomial=\\n\"); for(;i<=finishB;i++) printf(\"%d %d\\n\",a[i].coef,a[i].power); printf(\" \\n \\n Result polynomial=\\n\"); k=i; for(k=i;k #define MAX_TERMS 100 typedef struct { int row; int col; int value; }term; term a[MAX_TERMS]; int main() { int i,j; printf(\"Enter size of sparse matrix:\"); printf(\"Max rows=%d\",a[0].row); printf(\"Max col=%d\",a[0].col); printf(\"Total ele=%d \\n\",a[i].value); printf(\"Enter % elements \\n\",a[0].value); for(i=0;i typedef struct"} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 5, "text": "the matrix \\n); k=1; Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 8 for(i=0;i typedef struct { int row, col, value; }term; term a[20],b[20]; int main() { int i, n, j,current=0;; printf(\"Enter size of Matrix row & col and Total elemnts =\\n\" ); scanf(\"%d%d%d\", &a[0].row, &a[0].col,&a[0].value); printf(\" Enter sparse matrix elements\\n\"); for(i=1;i<=a[0].value;i++) { printf(\" row col and value=\"); scanf(\"%d%d%d\", &a[i].row, &a[i].col, &a[i].value); } printf(\" Transpose of sparse matrix\\n\\n\"); current=1; n=a[0].value; b[0].col=a[0].row; b[0].row=a[0].col; b[0].value=n; if(n>0) { for(i=0;i int main() { char greeting[6]={\u2018H\u2019,\u2019E\u2019,\u2019L\u2019,\u2019L\u2019,\u2019O\u2019}; printf(\u201cGreeting message : %s\\n\u201d,greeting); return 0; } Operations on string : 1. Strcpy(dest,src); This operation copies string source to destination string. int main() { char src[50],dest[50]; printf(\u201cEnter source\u201d); gets(src); printf(\u201cEnter destination string\u201d); gets(dest); strcpy(dest,src); printf(\u201cCopied string is %s\\n\u201d,dest); return 0; } Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 10 Strcat(dest,char) : This operation concatenates string string vhar into the end of the string dest. int main() { char src[20],dest[20]; strcpy(src,\u201dThis is source\u201d); strcpy(dest,\u201dThis is destination\u201d); strcat(dest,src); printf(\u201cFinal destination string is %s\\n\u201d,dest); return (0); } Strlen(str) : This operation returns thr length of the entered string str. int main() { char str[50]; int len; printf(\u201cEnter string\u201d); gets(str); len=strlen(str); printf(\u201cLength of %s is %d\\n\u201d,str,len); return (0); } Strcmp(s1,s2) : This returns 0 if s1 and s2 are same, less than 0 if s1s2. int main() { char s1[50],s2[50]; int ret; printf(\u201cEnter string s1\u201d); gets(s1); printf(\u201cEnter string s2\u201d); gets(s2); ret=strcmp(s1,s2); if(ret<0) { printf(\u201cs10) { printf(\u201cs1>s2\u201d); } else { printf(\u201cs1=s2\u201d); } Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 11 return (0); } Strchr(s1,s2) : This returns a pointer to the first occurrence of characterch in the string s1. int main() { const char s1=\u2019Tea & Biscuits\u2019; const char s2=\u2019&\u2019; char ret; ret=strchr(s1,ch); printf(\u201cString after %cis %s\u201d,ch,ret); return (0); } Strstr(s1,s2) : Returns a pointer to the first occurrence of string s2 in string s1. int main() { const char s1[50]=\u201dGlobal Academy of Technology\u201d; const char s2[50]=\u201dAcademy\u201d; char ret; ret=strstr(s1,s2); printf(\u201cThe substring is %s\\n\u201d,ret); return (0); } Char strncpy(dest,src) This operation copies only \u2018n\u2019 characters from src string intp destination string and returns dest string. Char strncat(dest,char) : This concatenates dest and only n characters from src, returning in dest."} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 6, "text": "s1[50]=\u201dGlobal Academy of Technology\u201d; const char s2[50]=\u201dAcademy\u201d; char ret; ret=strstr(s1,s2); printf(\u201cThe substring is %s\\n\u201d,ret); return (0); } Char strncpy(dest,src) This operation copies only \u2018n\u2019 characters from src string intp destination string and returns dest string. Char strncat(dest,char) : This concatenates dest and only n characters from src, returning in dest. Strcmp(s1,s2,n) This operation compares first \u2018n\u2019 characters of the string entered. Q9. What do you mean by pattern matching? Where do we use this concept? Pattern matching : A code to check if the given string is present in another string is pattern matching. For example : \u201cGlobal is present in Global Academy of Technology\u201d . If the string is present then its location is printed. Assume that we have two strings, string and pat, where pat is a pattern to be searched. If pattern is present in the string, then it returns its position else returns -1. it examines each character of the string until it finds the pattern or it reaches the end of the string. Example : #include #include int match(char[],char[]) int main() { char a[100],b[100]; Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 12 int position; printf(\u201cEnter text\\n\u201d); gets(a); printf(\u201cEnter a string to find\u201d); gets(b); position=match(a,b) if(position!=-1) { printf(\u201cFound at location %d\\n\u201d,position+1); } else { printf(\u201cNot found\u201d); } return (0); } int match(char text[],char pattern[]) { int c,d,e,txt_length,pattern_length,position=-1; txt_length=strlen(txt); pattern_length=strlen(pattern); if(pattern_length>txt_length) { return -1; } for(c=0;c<=txt_length-pattern_length;c++) { position=e=c; for(d=0;d int main() { int var = 20; int *ip; ip=&var; printf(\u201cAddress of variable is %x\\n\u201d, &var); printf(\u201cAddress stored in ip variable is :%x\u201d,ip); printf(\u201cvalue of *ip variable : %d\u201d, *ip); return 0; } Q12. Why do we need dynamic memory allocation techniques? Explain the functions available for allocating memory dynamically. Dynamic memory allocation : It refers to performing manual management for dynamic memory allocation using standard library functions such as malloc, realoc, calloc and free. The size of array initially declared can be sometimes insufficient or sometimes more than required but dynamic memory allocation allows a program to obtain more memory space, while running or to release space when not required. Functions: There are four standard library functions under \u201cstdlib.h\u201d for dynamic memory allocation. malloc() \u2013 It allocates requested size of bytes and returns a pointer first byte of allocated space. Syntax : ptr=(data_type *)malloc(bysize); Ex : (int*)malloc(100*sizeof(int)); calloc() \u2013 Allocates spaces for array elements, initializes to zero and then returns a pointer to memory. Syntax : ptr=(data_type*)calloc(n,element_size); Ex : ptr=(float*)calloc(25,sizeof(float)); realloc() \u2013 Changes the size of the previously allocated space according to the requirement. Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 16 Syntax : ptr=realloc(ptr,newsize); free() \u2013 It deallocates the previously allocated space. Syntax \u2013 free(ptr); Q13.What is sparse matrix? How to represent a sparse matrix? Sparse Matrix : If a matrix contains more zero entities then suc a matrix is called"} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 8, "text": "Dr. Ganga Holi, ISE Dept., Global academy of Technology 16 Syntax : ptr=realloc(ptr,newsize); free() \u2013 It deallocates the previously allocated space. Syntax \u2013 free(ptr); Q13.What is sparse matrix? How to represent a sparse matrix? Sparse Matrix : If a matrix contains more zero entities then suc a matrix is called a sparse matrix. Ex: [ 0 5 0 4 0 0 2 0 0 0 1 0 0 5 0 0 1 0 5 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 ] The concept of sparse matrix is used in scientific or engineering applications. Representation : Array representation : 2D array having n-rows and 3-coloumns,where n is number of non-zero elements. a[i][0] \u2013 represents row value a[i][1] \u2013 represents column value a[i][2] \u2013 represents matrix value 1 2 5 1 4 4 2 1 2 2 5 1 3 2 5 3 5 1 4 5 1 5 6 1 Array of structures representation : Triple values represent row, column, value. typedef struct { int row;int col;int value; }term; term a[MAX_TERMS]; 14. Define string. Explain string handling functions: strcat, strcpy, strcmp, strncmp, strncat, strchr, strrchr, strtok, strstr, strspn, strcspn, strbrk In C programming, array of character are called strings. A string is terminated by null character /0. For example: Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 17 \"c string tutorial\" Here, \"c string tutorial\" is a string. When, compiler encounters strings, it appends null character at the end of string. Declaration of strings Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type. char s[5]; Strings can also be declared using pointer. char *p Initialization of strings In C, string can be initialized in different number of ways. char c[]=\"abcd\"; OR, char c[5]=\"abcd\"; OR, char c[]={'a','b','c','d','\\0'}; OR; char c[5]={'a','b','c','d','\\0'}; String can also be initialized using pointers char *c=\"abcd\"; Reading words from user. char c[20]; scanf(\"%s\",c); String variable c can only take a word. It is beacause when white space is encountered, the scanf() function terminates. Write a C program to illustrate how to read string from terminal. #include int main() { char name[20]; Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 18 printf(\"Enter name: \"); scanf(\"%s\",name); printf(\"Your name is %s.\",name); return 0; } Output Enter name: Dennis Ritchie Your name is Dennis. Here, program will ignore Ritchie because, scanf() function takes only string before the white space. Reading a line of text C program to read line of text manually. #include int main() { char name[30],ch; int i=0; printf(\"Enter name: \"); while(ch!='\\n') // terminates if user hit enter { ch=getchar(); name[i]=ch; i++; } name[i]='\\0'; // inserting null character at end printf(\"Name: %s\",name); return 0; } This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively. int main() { char name[30]; printf(\"Enter name: \"); gets(name); //Function to read"} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 9, "text": "name[i]=ch; i++; } name[i]='\\0'; // inserting null character at end printf(\"Name: %s\",name); return 0; } This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively. int main() { char name[30]; printf(\"Enter name: \"); gets(name); //Function to read string from user. printf(\"Name: \"); puts(name); //Function to display string. return 0; } Both, the above program has same output below: Output: Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 19 Enter name: Tom Hanks Name: Tom Hanks String handling functions C compiler provides a library function called string.h. The functions supported by the header file string.h are: int strlen(char* str) length of the char array char* strcat(char* dest, char* src) concatenate dest and src strings return result in dest char* strcat(char* dest, char* src, int n) concatenate dest and n characters from src strings return result in dest char* strcpy(char* dest, char* src) copy src into dest ; return dest char* strncpy(char* dest, char* src, int n) copy n characters from src string into dest ; return dest char* strcmp(char* str1, char* str2) compares two strings . returns <0 if str10 if str1>str2 char* strcmpi(char* str1, char* str2) or char* stricmp(char* str1, char* str2) compares two strings . returns <0 if str10 if str1>str2 it ignores case. char* strcmp(char* str1, char* str2) compare first n characters of two strings . returns <0 if str10 if str1>str2 char* strchr(char*s, int c) returns pointer to the first occurrence of c in s; return NULL if not present. char* strrchr(char*s, int c) returns pointer to the last occurrence of c in s; return NULL if not present. char* strstr(char* s, char* pat) Return pointer to start of pat in s char* strtok(char* s, char delimiters) Return a token from s, token is surrounded by delimiters char* strspn(char* s, char* spanset) Scan s for characters in spanset , return length of span char* strcspn(char* s, char* spanset) Scan s for characters not in spanset , return length of span strlwr() converts from upper case to lower case struper() converts from upper case to lower case strrev() reverses a string strset(char* s, char c) It sets all characters in string to character c strnset(char* s, char c) It sets first n characters in string to character c 15. Write an algorithm for pattern/string matching. Simple string matching algorithm using brute force method is given below. Match(text, pat) { L1=strlen(text); Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 20 L2=strlen(pat); for(i=0;i<(L1-L2);i++) { j=0; while( j! =L2 && text[i+j] ==pat[j]) { j++; } If(j==L2) { flag=1; break; } } If(flag==1) printf(\u201cpattern found\u201d); else printf(\u201cNot found\u201d); } 16. Write a program to search an element using linear and binary search. Linear Search algorithm/function Search(a, key) { For(i=0;i #include #define SIZE 15 void create(int array[], int n) { int i; printf(\" Enter n elemnts\\n\"); for(i=1;i<=n;i++) { scanf(\"%d\",&array[i]); } return ; } void display(int array[], int n) { int i; printf(\" Elemnets of the array are\\n\"); for(i=1;i<=n;i++) { printf(\"%d\\t\",array[i]); } printf(\"\\n\"); } int insertAtPos(int array[], int n, int position, int value) { int i; for (i = n ; i >= position; i--) array[i+1] = array[i]; array[position] = value; n++; return n; } int deleteFromPos(int array[], int n, int position) { int i, v; v=array[position]; for (i = position; i < n; i++) array[i] = array[i+1]; Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 22 n--; return n; } int main() { int array[SIZE], n, choice, flag=0; int position, value; int count=0; char answer; while(1) { printf(\"1. Create\\n\"); printf(\"2. Display\\n\"); printf(\"3. Inserting Elemnt at given valid position\\n\"); printf(\"4. Deleting an Element at a given valid Position(POS)\\n\"); printf(\"5. Exit\\n\"); printf(\"Enter choice =\"); scanf(\"%d\", &choice); switch(choice) { case 1 : if(flag==0) { flag=1; printf(\"Enter no. of elements=\"); scanf(\"%d\", &n); // if n is > SIZE. Reduce n=SIZE if(n>SIZE) n=SIZE; create(array,n); } else { printf(\"Array is already created.cannot create again \"); } break; case 2 : display(array, n); break; case 3 : printf(\"Enter the location you wish to insert an element=\\n\"); scanf(\"%d\", &position); if(position>=SIZE || position>n+1) { printf(\"IT is not valid Position\"); break; } printf(\"Enter the value to insert=\\n\"); scanf(\"%d\", &value); n=insertAtPos(array, n, position, value); break; case 4 : printf(\"Enter the location you wish to delete an element=\\n\"); scanf(\"%d\", &position); if(position>n) { printf(\"Postion is beyond the array element\\n\"); break; } if(n==0) { Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 23 printf(\"Array is empty\\n\"); break; } n=deleteFromPos(array, n, position); break; case 5 : return 0; default : printf(\" Please enter correct choice\"); break; } } return 0; } 18. Write a program to sort the numbers using selection and bubble sort algorithms. Ans:1) SELECTION SORT: #include int main() { int array[100], n, i,j, position, swap; printf(\"Enter number of elements\\n\"); scanf(\"%d\", &n); printf(\"Enter %d integers\\n\", n); for ( i ="} {"pdf_name": "DS_Module I_GangaHoli.pdf", "chunk_id": 11, "text": "correct choice\"); break; } } return 0; } 18. Write a program to sort the numbers using selection and bubble sort algorithms. Ans:1) SELECTION SORT: #include int main() { int array[100], n, i,j, position, swap; printf(\"Enter number of elements\\n\"); scanf(\"%d\", &n); printf(\"Enter %d integers\\n\", n); for ( i = 0 ; i< n ; i++ ) scanf(\"%d\", &array[i]); for ( i = 0 ; i < ( n - 1 ) ; i++ ) { position = i; for ( j = i + 1 ; j < n ; j++ ) { if ( array[position] > array[j] ) position = j; } if ( position != i ) { swap = array[i]; array[i] = array[position]; array[position] = swap; } } printf(\"Sorted list in ascending order:\\n\"); for ( i = 0 ; i< n ; i++ ) printf(\"%d\\n\", array[i]); return 0; } Module I-Arrays, Strings, Dr. Ganga Holi, ISE Dept., Global academy of Technology 24 2)BUBBLE SORT: #include int main() { int data[100],i,n,step,temp; printf(\"Enter the number of elements to be sorted: \"); scanf(\"%d\",&n); for(i=0;idata[i+1]) /* To sort in descending order, change > to < in this line. */ { temp=data[i]; data[i]=data[i+1]; data[i+1]=temp; } } } printf(\"In ascending order: \"); for(i=0;i #define MAX_DESCRIPTION_LENGTH 100 #define MAX_DAY_NAME_LENGTH 20 struct Day { char dayName[MAX_DAY_NAME_LENGTH]; int date; char activityDescription[MAX_DESCRIPTION_LENGTH]; }; struct Day weekCalendar[7]; void read() { for (int i = 0; i < 7; ++i) { printf(\"Enter day name for day %d: \", i + 1); scanf(\"%s\", weekCalendar[i].dayName); printf(\"Enter date for day %d: \", i + 1); scanf(\"%d\", &weekCalendar[i].date); printf(\"Enter activity description for day %d: \", i + 1); scanf(\" %[^\\n]s\", weekCalendar[i].activityDescription); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 2 } } void display() { printf(\"\\n--- Calendar ---\\n\"); for (int i = 0; i < 7; ++i) { printf(\"Day %d: %s, Date: %d, Activity: %s\\n\", i + 1, weekCalendar[i].dayName, weekCalendar[i].date, weekCalendar[i].activityDescription); } } int main() { printf(\"Enter details for each day of the week:\\n\"); read(); display(); return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 3 2. Develop a Program in C for the following operations on Strings. a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP) b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in STR Support the program with functions for each of the above operations. Don't use Built-in functions. #include #include void read(char *s) { gets(s); } void strcopy(char *s1,char *s2) { int i; for(i=0;s2[i]!='\\0';i++) s1[i]=s2[i]; s1[i]='\\0'; } int matchnreplace(char *str,char *pat,char *rep) { char ans[100]; int i=0,m=0,c=0,j=0,flag=0,k; while(str[c]!='\\0') { if (str[m]==pat[i]) { i++; m++; if(pat[i]=='\\0') { flag=1; for(k=0;rep[k]!='\\0';k++,j++) ans[j]=rep[k]; i=0; c=m; } } else { ans[j]=str[c]; j++;c++;m=c;i=0; } } ans[j]='\\0'; strcopy(str,ans); return flag; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 4 int main() { char str[100],pat[20],rep[20]; int flag=0; clrscr(); printf(\"Enter the string\"); read(str); printf(\"Enter the pattern\"); read(pat); printf(\"Enter the string to be replaced\"); read(rep); flag=matchnreplace(str,pat,rep); if(flag==1) printf(\"The string is found %s\",str); else printf(\"The pattern is not found\"); return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 5 3. Develop a menu driven Program in C for the following operations on STACK of Integers (Array Implementation of Stack with maximum size MAX) a. Push an Element on to Stack b. Pop an Element from Stack c. Demonstrate how Stack can be used to check Palindrome d. Demonstrate Overflow and Underflow situations on Stack e. Display the status of Stack f. Exit Support the program with appropriate functions for each of the above"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 5, "text": "a. Push an Element on to Stack b. Pop an Element from Stack c. Demonstrate how Stack can be used to check Palindrome d. Demonstrate Overflow and Underflow situations on Stack e. Display the status of Stack f. Exit Support the program with appropriate functions for each of the above operations. #include #define MAX 10 int top=-1; int overflow() { if (top==MAX-1) return 1; else return 0; } int underflow() { if (top==-1) return 1; else return 0; } void push(int *s,int ele) { if(!overflow()) s[++top]=ele; else printf(\"stack overflow\\n\"); } int pop(int *s) { if(!underflow()) return(s[top--]); else printf(\"stack underflow\\n\"); return(0); } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 6 void display(int *s) { int i; if(underflow()) { printf(\"stack underflow\\n\"); return; } printf(\"The stack contents are:\\n\"); for(i=0;i<=top;i++) printf(\"%d\\t\",s[i]); } int palin(char *pal,int *s) { int i; top=-1; for(i=0;pal[i]!='\\0';i++) push(s,pal[i]-'0'); for(i=0;pal[i]!='\\0';i++) if (pal[i]!=(pop(s)+'0')) return 0; return 1; } int main() { int stack[MAX],ch,i,j,ele,p; char str[10]; while(1) { printf(\"\\nEnter your choice:\\n1:PUSH\\n2:POP\\n3:CHECK PALINDROME\\n4:DISPALY\\n5.EXIT\\n\"); scanf(\"%d\",&ch); switch(ch) { case 1: printf(\"\\nEnter the element to be pushed: n\"); scanf(\"%d\",&ele); push(stack,ele); break; case 2: ele=pop(stack); if(ele!=0) printf(\"\\nThe deleted element is: %d\\n\",ele); break; case 3:printf(\"\\nEnter the string \"); fflush(stdin); gets(str); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 7 p=palin(str,stack); if(p) printf(\"\\nThe given string is Palindrome\"); else printf(\"\\nThe given string is not a palindrome\"); break; case 4:display(stack); break; default:exit(0); } } return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 8 4. Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands. #include char stack[100]; int top=-1; void push(char x) { stack[++top]=x; } char pop() { char ret; ret=stack[top]; stack[top]='\\0'; top--; return ret; } int inper(char ch) { switch(ch) { case '+': case '-': return 1; case '*': case '/': return 3; } } int stper(char ch) { switch(ch) { case '+': case '-': return 2; case '*': case '/': return 4; case '(': return 0; case '#': return -1; } } void convert(char *exprn,char *postfix) DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 9 { int n=0,i=0,j=0; char ch; ch=exprn[i++]; while(ch!='#') { switch(ch) { case '(': push(ch); break; case ')': while(stack[top]!='(') postfix[j++]=pop(); pop(); break; case '+': case '-': case '*': case '/': while(stper(stack[top])>=inper(ch)) postfix[j++]=pop(); push(ch); break; default: postfix[j++]=ch; break; } printf(\"\\nSTACK=%s POSTFIX = %s\",stack,postfix); ch=exprn[i++]; } while(stack[top]!='#') postfix[j++]=pop(); postfix[j]='\\0'; } void main() { char exprn[20]=\"\",postfix[20]=\"\"; int i; printf(\"\\n Enter the postfix expn\\t\"); scanf(\"%s\",exprn); strcat(exprn,\"#\"); push('#'); convert(exprn,postfix); printf(\"\\n After Evaluation %s\",postfix); } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 10 5. Develop a Program in C for the following Stack Applications a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %,^ b. Solving Tower of Hanoi problem with n disks. 5 a)"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 6, "text": "BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 10 5. Develop a Program in C for the following Stack Applications a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %,^ b. Solving Tower of Hanoi problem with n disks. 5 a) #include #include #include #include int stack[100]; int top=-1; char exprn[20]; void push(int ele) { stack[++top]=ele; } int pop() { return (stack[top--]); } void compute(int opr1,char ch,int opr2) { switch(ch) { case '+' : push(opr1 + opr2); break; case '-' : push(opr1 - opr2); break; case '*' : push(opr1 * opr2); break; case '/' : if(opr2!=0) push(opr1/opr2); else { printf(\"\\nDivide by Zero Error\"); exit(0); } break; } } int eval() { int n=0,i=0,flag=1; char ch; int opr1,opr2; ch=exprn[i++]; while(ch!='#') { DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 11 printf(\"\\n%c\",ch); switch(ch) { case '+': case '-': case '*': case '/': opr2=pop(); opr1=pop(); printf(\"\\n%d %d %c\",opr1,opr2,ch); compute(opr1,ch,opr2); break; default: push(ch-'0'); } ch = exprn[i++]; } return pop(); } void main() { printf(\"\\n Enter the postfix expn\\t\"); scanf(\"%s\",exprn); strcat(exprn,\"#\"); printf(\"\\n After Evaluation %d\",eval()); } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 12 5 b) #include #define MAX 10 typedef struct { int n; int from; int to; int auxi; int ret; // which case to return }stack; int top = -1; stack st[MAX]; int empty() { return top==-1; } stack pop() { return st[top--]; } void push(int n,int beg,int to,int aux,int ret) { top++; st[top].n = n; st[top].from = beg; st[top].to = to; st[top].auxi = aux; st[top].ret = ret; } void hanoi(int n,int beg,int aux, int end) { stack t; int nmoves=0; int ret=1,temp,i; while(1) { switch(ret) { case 1:if (n==1) { printf(\"\\nMove %d: Move Disk %d from %c to %c\",++nmoves,n,beg,end); ret=5; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 13 } else ret=2; break; case 2: push(n,beg,end,aux,3); --n; temp=end; end=aux; aux=temp; ret=1; break; case 3: printf(\"\\nMove %d: Move Disk %d from %c to %c\",++nmoves,n,beg,end); case 4: push(n,beg,end,aux,5); --n; temp=beg; beg=aux; aux=temp; ret=1; break; case 5: if(empty()) return; t=pop(); n=t.n; beg=t.from; aux=t.auxi; end=t.to; ret=t.ret; break; } /*printf(\"\\n Stack Content\"); for(i=top;i>=0;i--) printf(\"\\n%d %d %d %d\",st[i].n,st[i].from,st[i].to,st[i].auxi);*/ } } int main() { int n; printf(\"\\nEnter number of disks\"); scanf(\"%d\",&n); hanoi(n,'A','C','B'); return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 14 6. Develop a menu driven Program in C for the following operations on Circular QUEUE of Characters (Array Implementation of Queue with maximum size MAX) a. Insert an Element on to Circular QUEUE b. Delete an Element from Circular QUEUE c. Demonstrate Overflow and Underflow situations on Circular QUEUE d. Display the status of Circular QUEUE e. Exit Support the program with appropriate functions for each of the above operations #include #include #define MAX_SIZE 5 int Queue[MAX_SIZE]; int front = -1; int rear = -1; int count = 0; int Qfull() { return count == MAX_SIZE; } int Qempty()"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 7, "text": "d. Display the status of Circular QUEUE e. Exit Support the program with appropriate functions for each of the above operations #include #include #define MAX_SIZE 5 int Queue[MAX_SIZE]; int front = -1; int rear = -1; int count = 0; int Qfull() { return count == MAX_SIZE; } int Qempty() { return count == 0; } void insert(int ele) { rear=(rear+1) % MAX_SIZE; Queue[rear]=ele; count++; if(front == -1) front++; } int deleteq() { int ret; ret=Queue[front]; front=(front+1) % MAX_SIZE; count--; return(ret); } void display() { int i,j; if(Qempty()) printf(\"\\n Queue is empty\\n\"); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 15 else { j=front; printf(\"\\n Elements in the Queue\\n\"); for(i=0;i #include struct student { char USN[10]; char Name[20]; char Branch[15]; char Sem[3]; char PhNo[10]; }; typedef struct student STU; struct node { STU info; struct node *link; }; typedef struct node* Node; STU GetData() { STU temp; printf(\"Enter the usn: \"); fflush(stdin); gets(temp.USN); printf(\"\\nEnter the Name:\"); fflush(stdin); gets(temp.Name); printf(\"\\nEnter branch:\"); fflush(stdin); gets(temp.Branch); printf(\"\\nEnter sem:\"); fflush(stdin); gets(temp.Sem); printf(\"\\nEnter the phone number:\"); fflush(stdin); gets(temp.PhNo); return temp; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 17 void displayRec(STU ele) { printf(\"\\n%s\\t\\t\",ele.USN); printf(\"%s\\t\\t\",ele.Name); printf(\"%s\\t\",ele.Branch); printf(\"%s\\t\",ele.Sem); printf(\"%s\\n\",ele.PhNo); } Node Create(STU ele) { Node temp; temp=(Node)malloc(sizeof(struct node)); temp->info=ele; temp->link=NULL; return temp; } Node Finsert(Node first,STU ele) { Node temp=Create(ele); if(first== NULL) first=temp; else { temp->link=first; first = temp; } return first; } Node Einsert(Node first,STU ele) { Node temp=Create(ele),cur; if(first== NULL) first=temp; else { //for(cur=first;cur->link!=NULL;cur=cur->link); cur=first; while(cur->link!=NULL) cur=cur->link; cur->link=temp; } return first; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 18 void display(Node first) { Node temp=first; if(temp == NULL) printf(\"\\nList is empty\\n\"); else { printf(\"\\nStudent Details in the list\\n\"); printf(\"USN\\t\\tName\\t\\tBranch\\tSem\\tPhno\\n\"); while(temp!=NULL) { displayRec(temp->info); temp=temp->link; } } } int Count(Node first) { Node temp=first; int cnt=0; if(temp == NULL) printf(\"\\nList is empty\\n\"); else { while(temp!=NULL) { cnt++; temp=temp->link; } } return cnt; } Node Fdelete(Node first) { Node temp=first; if(first=="} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 8, "text": "printf(\"\\nList is empty\\n\"); else { printf(\"\\nStudent Details in the list\\n\"); printf(\"USN\\t\\tName\\t\\tBranch\\tSem\\tPhno\\n\"); while(temp!=NULL) { displayRec(temp->info); temp=temp->link; } } } int Count(Node first) { Node temp=first; int cnt=0; if(temp == NULL) printf(\"\\nList is empty\\n\"); else { while(temp!=NULL) { cnt++; temp=temp->link; } } return cnt; } Node Fdelete(Node first) { Node temp=first; if(first== NULL) printf(\"\\nList is empty\"); else { temp=first; printf(\"\\nElement Deleted is\\n\"); printf(\"USN\\t\\tName\\t\\tBranch\\tSem\\tPhno\\n\"); displayRec(temp->info); first = first->link; free(temp); } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 19 return first; } Node Edelete(Node first) { Node temp=first,t; if(first== NULL) printf(\"\\nList is empty\"); else if(first->link==NULL) { printf(\"\\nElement Deleted is\\n\"); printf(\"USN\\t\\tName\\t\\tBranch\\tSem\\tPhno\\n\"); displayRec(first->info); first=NULL; } else { //for(temp=first;temp->link->link!=NULL;temp=temp->link); while(temp->link->link!=NULL) temp=temp->link; printf(\"\\nElement Deleted is\\n\"); printf(\"USN\\t\\tName\\t\\tBranch\\tSem\\tPhno\\n\"); displayRec(temp->link->info); t = temp->link; temp->link=NULL; free(t); } return first; } void main() { Node first=NULL; int flag=1,ch; STU ele; while(flag) { printf(\"\\n Menu \\n\"); printf(\"\\n1 Front Insert\\n2 End Insert\\n3 Front Delete\\n4 End Delete\\n5 Display\\n6 No. of Nodes in the list\\n\"); printf(\"7 Exit\\n Enter the Choice\"); scanf(\"%d\",&ch); switch(ch) { case 1: printf(\"\\n Enter the Student Details \\t\"); ele=GetData(); first=Finsert(first,ele); break; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 20 case 2: printf(\"\\n Enter the Student Details \\t\"); ele=GetData(); first=Einsert(first,ele); break; case 3: first=Fdelete(first); break; case 4: first=Edelete(first); break; case 5: display(first); break; case 6: printf(\"\\n the Number of Node in list %d\\t\",Count(first)); break; default: flag = 0; } } } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 21 8. Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation,Sal, PhNo a. Create a DLL of N Employees Data by using end insertion. b. Display the status of DLL and count the number of nodes in it c. Perform Insertion and Deletion at End of DLL d. Perform Insertion and Deletion at Front of DLL e. Demonstrate how this DLL can be used as Double Ended Queue. f. Exit #include #include struct Employee { char SSN[10]; char Name[10]; char Branch[10]; char Des[10]; char sal[10]; char phone[10]; }; typedef struct Employee EMP; struct node { EMP info; struct node *lptr,*rptr; }; typedef struct node* Node; Node front=NULL,rear=NULL; EMP GetRec() { EMP temp; printf(\"Enter the SSN: \"); fflush(stdin); gets(temp.SSN); printf(\"Enter the Name:\"); fflush(stdin); gets(temp.Name); printf(\"Enter branch:\"); fflush(stdin); gets(temp.Branch); printf(\"Enter the designation: \"); fflush(stdin); gets(temp.Des); printf(\"Enter sal:\"); fflush(stdin); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 22 gets(temp.sal); printf(\"Enter the phone number:\"); fflush(stdin); gets(temp.phone); return temp; } void DispRec(EMP temp) { printf(\"%s\\t\",temp.SSN); printf(\"%s\\t\",temp.Name); printf(\"%s\\t\",temp.Branch); printf(\"%s\\t\",temp.Des); printf(\"%s\\t\",temp.sal); printf(\"%s\\n\",temp.phone); } Node Create(EMP ele) { Node temp; temp=(Node)malloc(sizeof(struct node)); temp->info=ele; temp->lptr=NULL; temp->rptr=NULL; return temp; } void Finsert(EMP ele) { Node temp=Create(ele); if(front== NULL) { front=temp; rear=temp; } else { temp->rptr=front; front->lptr=temp; front = temp; } } void Einsert(EMP ele) { Node temp=Create(ele); if(rear == NULL) { front=temp; rear=temp; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 23 } else { rear->rptr=temp; temp->lptr=rear;"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 9, "text": "{ Node temp=Create(ele); if(front== NULL) { front=temp; rear=temp; } else { temp->rptr=front; front->lptr=temp; front = temp; } } void Einsert(EMP ele) { Node temp=Create(ele); if(rear == NULL) { front=temp; rear=temp; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 23 } else { rear->rptr=temp; temp->lptr=rear; rear=temp; } } void Fdelete() { Node temp=front; if(front == NULL) printf(\"\\nList is empty\"); else { temp=front; printf(\"\\nDeleted Employee Records \\n\"); DispRec(temp->info); front = front->rptr; front->lptr= NULL; if(front == NULL) rear = NULL; free(temp); } } void Edelete() { Node temp=rear,t; if(rear== NULL) printf(\"\\nList is empty\"); else if(rear->lptr == NULL) { printf(\"\\nDeleted Employee Records \\n\"); DispRec(rear->info); front=rear=NULL; free(temp); } else { rear = rear->lptr; rear->rptr=NULL; printf(\"\\nDeleted Employee Records \\n\"); DispRec(temp->info); free(temp); } } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 24 void display(Node front) { Node temp=front; if(temp == NULL) printf(\"\\nList is empty\\n\"); else { printf(\"\\nEmployee Records list\\n\"); while(temp!=NULL) { DispRec(temp->info); temp=temp->rptr; } } } void main() { EMP ele; int flag=1,ch; while(flag) { printf(\"\\n Menu Implementation of Double Ended Queue using DLL\\n\"); printf(\"\\n1 Insert Front \\n2 Insert rear \\n3 Delete Front \\n4 Delete Rear \\n5 Display\\n\"); printf(\"6 Exit\\n Enter the Choice\"); scanf(\"%d\",&ch); switch(ch) { case 1: printf(\"\\n Enter the Employee Record to Insert Front of Queue\\n\"); ele = GetRec(); Finsert(ele); break; case 2: printf(\"\\n Enter the Employee Record to Insert Front of Queue\\n\"); ele=GetRec(); Einsert(ele); break; case 3: Fdelete(); break; case 4: Edelete(); break; case 5: display(front); break; default: flag = 0; } } } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 25 9. Develop a Program in C for the following operationson Singly Circular Linked List (SCLL) with header nodes a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3 b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in POLYSUM(x,y,z). Support the program with appropriate functions for each of the above operations #include #include #include struct term { int coeff; int pow_x; int pow_y; int pow_z; }; typedef struct term TERM; struct node { TERM info; struct node* next; }; typedef struct node* Node; Node Create(TERM t) { Node temp = (Node)malloc(sizeof(struct node)); temp->info=t; temp->next = temp; return temp; } Node MKHeader() { TERM x; Node temp; x.coeff=-1; x.pow_x=-1; x.pow_y=-1; x.pow_z=-1; temp=Create(x); return temp; } Node Insert(Node p,TERM t) { Node temp = Create(t),cur=p; while(cur->next!=p) cur=cur->next; cur->next=temp; temp->next=p; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 26 return p; } double Compute(Node temp,int x,int y,int z) { double ret; TERM t=temp->info; ret=t.coeff * pow(x, t.pow_x) * pow(y, t.pow_y) * pow(z,t.pow_z); return ret; } double Evaluate(Node p, int x, int y, int z) { Node po = p->next; double sum = 0; while (po!=p) { sum += Compute(po,x,y,z); po = po->next; } return sum; } void DispTerm(TERM t) { printf(\" %dx^%dy^%dz^%d \", t.coeff, t.pow_x, t.pow_y, t.pow_z); } void PrintPoly(Node p) { Node po = p->next; while (po!=p) { DispTerm(po->info); if(po->next!=p) printf(\"+\");"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 10, "text": "int z) { Node po = p->next; double sum = 0; while (po!=p) { sum += Compute(po,x,y,z); po = po->next; } return sum; } void DispTerm(TERM t) { printf(\" %dx^%dy^%dz^%d \", t.coeff, t.pow_x, t.pow_y, t.pow_z); } void PrintPoly(Node p) { Node po = p->next; while (po!=p) { DispTerm(po->info); if(po->next!=p) printf(\"+\"); po = po->next; } printf(\"\\n\"); } void ReadPoly(Node t1,int n) { TERM t; int i; for(i=1;i<=n;i++) { printf(\"Enter the value of coefficent and powers of x,y and z\"); scanf(\"%d%d%d%d\",&t.coeff,&t.pow_x,&t.pow_y,&t.pow_z); t1 = Insert(t1, t); } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 27 PrintPoly(t1); } int ComparePower(TERM m,TERM n) { if(m.pow_x==n.pow_x && m.pow_y==n.pow_y && m.pow_z==n.pow_z) return 1; else return 0; } TERM AddTerms(TERM m,TERM n) { TERM temp; temp.coeff=m.coeff+n.coeff; temp.pow_x = m.pow_x; temp.pow_y = m.pow_y; temp.pow_z = m.pow_z; return temp; } Node AddPoly(Node p1,Node p2) { Node Newlist=MKHeader(); Node t1=p1->next,t3; Node t2=p2->next,t4; TERM res; int i,flag; t3=t1; t4=t2; while(t1!=p1) { t2=p2->next; flag=1; while(t2!=p2 && flag) { if(ComparePower(t1->info,t2->info)) { res=AddTerms(t1->info,t2->info); Newlist=Insert(Newlist,res); flag=0; } t2=t2->next; } if (flag==1) Newlist=Insert(Newlist,t1->info); t1=t1->next; } while(t4!=p2) DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 28 { t3=Newlist->next; flag=1; while(t3!=Newlist && flag) { if(ComparePower(t3->info,t4->info)) flag=0; t3=t3->next; } if (flag==1) Newlist=Insert(Newlist,t4->info); t4=t4->next; } return Newlist; } int main() { int n,x,y,z,ch,i,coeff; Node polysum; Node poly1 = MKHeader(); Node poly2 = MKHeader(); while(1) { printf(\"\\nMenu\\n 1:Evaluate Polynomial \\n 2:Add\\n 3:Exit\\n Enter your choice\\n\"); scanf(\"%d\",&ch); switch(ch) { case 1: printf(\"Enter the terms in the polynomial\"); scanf(\"%d\",&n); ReadPoly(poly1,n); printf(\"Enter the values of x,y and z\"); scanf(\"%d%d%d\",&x,&y,&z); printf(\"%.2f\\n\", Evaluate(poly1, x, y, z)); break; case 2: printf(\"Enter the terms in the polynomial 2\"); scanf(\"%d\",&n); ReadPoly(poly2,n); polysum = AddPoly(poly1, poly2); PrintPoly(polysum); break; case 3: exit(0); } } return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 29 10. Develop a menu driven Program in C for the following operations on Binary Search Tree (BST) of Integers . a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2 b. Traverse the BST in Inorder, Preorder and Post Order c. Search the BST for a given element (KEY) and report the appropriate message d. Exit #include struct node { struct node *left; int data; struct node *right; }; typedef struct node* Node; Node newNode(int item) { Node temp = (Node)malloc(sizeof(struct node)); temp->data = item; temp->left = temp->right = NULL; return temp; } Node insert(Node node, int key) { if (node == NULL) return newNode(key); if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 30 return node; } int search(Node root, int key) { if (root == NULL) return -1; if(root->data == key) return 1; if (root->data < key) return search(root->right, key); return search(root->left, key); } void inorder(Node root) { if (root != NULL) { inorder(root->left); printf(\"%d \\t\", root->data); inorder(root->right); } } void preorder(Node root) {"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 11, "text": "node; } int search(Node root, int key) { if (root == NULL) return -1; if(root->data == key) return 1; if (root->data < key) return search(root->right, key); return search(root->left, key); } void inorder(Node root) { if (root != NULL) { inorder(root->left); printf(\"%d \\t\", root->data); inorder(root->right); } } void preorder(Node root) { if (root != NULL) { printf(\"%d \\t\", root->data); preorder(root->left); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 31 preorder(root->right); } } void postorder(Node root) { if (root != NULL) { postorder(root->left); postorder(root->right); printf(\"%d \\t\", root->data); } } int main() { int n,i,ch,ch1,key,pos; Node root=NULL; printf(\"Enterthe no of nodes in the BST\\n\"); scanf(\"%d\",&n); for(i=1;i<=n;i++) { printf(\"Enter the element to be iserted\\n\"); scanf(\"%d\",&key); root=insert(root,key); } while(1) { printf(\"\\nEnter the choice\\n1: Insert Node\\n2: Traversal\\n3: Search for key\\n4: Exit\\n\"); DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 32 scanf(\"%d\",&ch); switch(ch) { case 1: printf(\"Enter the element to be iserted\\n\"); scanf(\"%d\",&key); root=insert(root,key); break; case 2: printf(\"Enter your choice\\n1: Preorder\\n2: Inorder\\n3: Postorder\\n\"); scanf(\"%d\",&ch1); switch(ch1) { case 1: preorder(root); break; case 2: inorder(root); break; case 3: postorder(root); break; default: printf(\"\\n Make Correct Choice\"); } break; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 33 case 3: printf(\"Enter the key to be searched\\n\"); scanf(\"%d\",&key); pos=search(root,key); if (pos==-1) printf(\"\\n Key is not found\\n\"); else printf(\"\\n Key is found\\n\"); break; case 4: exit(0); } } return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 34 11. Develop a Program in C for the following operations on Graph(G) of Cities a. Create a Graph of N cities using Adjacency Matrix. b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS method #include #include int count=0; void creategraph(int n,int a[10][10]) { int i,j; printf(\"enter the adjacency matrix\\n\"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf(\"%d\",&a[i][j]); } void bfs(int a[10][10], int n, int source,int s[]) { int f,r,q[10],u,v,i; printf(\"enter the source vertex\\n\"); scanf(\"%d\",&source); printf(\"the nodes reachable are\\n\"); for(i=1;i<=n;i++) s[i]=0; f=r=0; q[r]=source; s[source]=1; while(f<=r) { u=q[f++]; for(v=1;v<=n;v++) { if(a[u][v]==1 && s[v]==0) { printf(\"\\n%d\",v); s[v]=1; q[++r]=v; } } } } void dfs(int a[10][10],int n,int vis[],int v) { int i; count++; vis[v]=count; DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 35 for(i=1;i<=n;i++) { if(vis[i]==0 && a[v][i]==1) dfs(a,n,vis,i); } } int main() { int a[20][20],n,source,s[10],i,j,vis[10]; int ch; while(1) { printf(\"\\nEnter your choice\\n1:Create graph\\n2:Check Reachability\\n3:Check Connectivity\\n4.Exit\\n\"); scanf(\"%d\",&ch); switch(ch) { case 1: printf(\"Enter the number of nodes:\"); scanf(\"%d\",&n); creategraph(n,a); break; case 2: bfs(a,n,source,s); break; case 3:for(i=1;i<=n;i++) vis[i]=0; dfs(a,n,vis,1); if(count==n) printf(\"the graph is connected\\n\"); else printf(\"the graph is not connected\\n\"); break; case 4: exit(0); } } return 0; } DATA STRUCTURES LABORATORY BCSL305 Department of Computer Science and Engineering, Sir MVIT Page | 36 12. Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine the records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory locations with L as"} {"pdf_name": "III Sem_DS_LAB_MANUAL_BCSL305_2023-24-1.pdf", "chunk_id": 12, "text": "and Engineering, Sir MVIT Page | 36 12. Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine the records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory locations with L as the set of memory addresses (2-digit) of locations in HT. Let the keys in K and addresses in L are Integers. Develop a Program in C that uses Hash function H: K \u2192L as H(K)=K mod m (remainder method), and implement hashing technique to map a given key K to the address space L. Resolve the collision (if any) using linear probing. #include #include #definre max 100 int create(int num) { int key; key=num%100; return key; } void linear_prob(int a[max],int key,int num) { int flag=0,i,count=10; if(a[key]==-1) a[key]=num; else { for(i=10;i