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, ….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<i<n. Top=- 1 Top=0 A Top=1 B A Top=2 C B A Top=3 D C B A Top=2 C B A Top=1 B A Top=0 A Top=- 1 Top=0 E Push Push Push Push Pop Pop Pop Pop Push Figure 1. Stack operations. Stack can be represented in the following ways Static implementation using array representation. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 2 Array representation of stacks Stacks may be represented using one way list ot linear representation that is 1D array. Stack will be maintained by 1 D array of elements. Elements can be of any data types: Basic, derived, user defined data types. Index variable TOP or pointer TOP is used to represent the location of the top of the stack element. Stack Operations 1. Stack full


is 1D array. Stack will be maintained by 1 D array of elements. Elements can be of any data types: Basic, derived, user defined data types. Index variable TOP or pointer TOP is used to represent the location of the top of the stack element. Stack Operations 1. Stack full 2. Stack empty 3. Push 4. Pop 5. Display 6. Top of stack Algorithms for stack operations int stackFull() { if(top==(max_size-1)) Return 1; else Return 0; } int stackEmpty() { if(top==-1)) return 1; else return 0; } void push(int ele) //Inserting element into the stack { if(stackFull()) { printf("\nStack Overflow:"); return; } stack[++top]=item; } int pop() //deleting an element from the stack { if(stackFull()) { printf("\nStack Overflow:"); return -1; } Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 3 return stack[top--]; } void display() { int i; if(stackEmpty()) { printf("\nStack is Empty:"); return; } printf("\nThe stack elements are:\n" ); for(i=top;i>=0;i--) printf("%d\n",stack[i]); } int topStack() { return(stack[top]; } // Complete program for stack operations #include<stdlib.h> #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”); else printf("Poped element =%d\n”, 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 • 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. • Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack. • Evaluation of Expressions • Conversion from Infix to Postfix, prefix • 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


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<strlen(p);i++) { sym=p[i]; if(sym>='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 – 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 ) ) – 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 ) ) – 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


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


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. –a+b-c+d c. a*(-b)+c -→ ans: ab-*c+ here no. of operators equal to no. of operands. So there has to be one unary operator… So –b 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 -→ ele=S1[top--] Stack 2 :Push -- S2[--bot]=ele Pop -→ ele=S2[top++] Single array can be used to represent multiple stacks by dividing into equal number of parts. i=0 I=N……….. I=2N……….. I=3N- I=3N……….. ………. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 9 …………….i<N I=2N-1 1 I=4N-1 Recursion A recursive function is a function which either calls itself or is in a potential cycle of function calls. As the definition specifies, there are two types of recursive functions. Consider a function which calls itself: we call this type of recursion immediate recursion and indirect recursion. Ex: Factorial is immediate recursive function. void A() { B(); return; } void B() { C(); return; } void C() { A(); return; } A recursive function must have the following two properties. 1. There must be certain criteria, called base criteria, for which the function does not call itself. Also called terminating condition to terminate the recursive call. 2. Each time function does call itself with the reduced value or the value must be closer to the base criteria. A Recursive function with these two properties is said to be well defined. Example. Factorial function 1. If n=0 then n!=1 → base criteria 2. If n>0 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,….. 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–Péter function The two-argument Ackermann–Péter function, is defined as follows for nonnegative integers m and n: 𝑨(𝒎, 𝒏) = { 𝒏+ 𝟏 𝒊𝒇𝒎= 𝟎


0,1,1,2,3,5,8,13,21,….. 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–Péter function The two-argument Ackermann–Péter function, is defined as follows for nonnegative integers m and n: 𝑨(𝒎, 𝒏) = { 𝒏+ 𝟏 𝒊𝒇𝒎= 𝟎 𝑨(𝒎−𝟏, 𝟏) 𝒊𝒇 𝒎> 𝟎 𝒂𝒏𝒅 𝒏= 𝟎 𝑨(𝒎−𝟏, 𝑨(𝒎, 𝒏−𝟏)) 𝒊𝒇 𝒎> 𝟎 𝒂𝒏𝒅 𝒏> 𝟎 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 − 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 − • Only one disk can be moved among the towers at any given time. • Only the "top" disk can be removed. • No large disk can sit over a small disk. Tower of hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation shows that a puzzle with 3 disks has taken 23−1 = 7 steps. Step 1 − Move n-1 disks from source to temp Step 2 − Move nth disk from source to dest Step 3 − Move n-1 disks from temp to dest N=1 Step 1 − Move nth disk from source(A) to dest(C) N=2 Step 1 − Move n-1=1 disk from source(A) to temp(B) Step 2 − Move nth =2 disk from source(A) to dest(C) Step 3 − 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(“move %d disk from %c to %c”, source,dest); else { tower(n - 1, source, dest,temp) // Step 1 printf(“move %d disk from %c to %c”, 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


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


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<stdio.h> #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. • In circular queue the last node is connected back to the first node to make a circle. • Elements are added at the rear end and the elements are deleted at front end of the queue • Both the front and the rear pointers points to the beginning of the array. • It is also called as “Ring buffer”. Circular Queue can be created in three ways they are · Using linked list · 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


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 “circular queue overflow “ 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 “circular queue underflow “ 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<stdio.h> #include<conio.h> #include<stdlib.h> #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<count; i++) { printf("%c ",q[j]); Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 21 j=(j+1)%SIZE; } printf("\n"); } int main() { char ch; for(;;) { printf("\n Circular 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; } } } Dequeues-


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; } } } Dequeues- Double Ended Queues Double Ended Queue is also a Queue data structure in which the insertion and deletion operations are performed at both the ends (front and rear). That means, we can insert at both front and rear positions and can delete from both front and rear positions. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 22 • Input Restricted Double Ended Queue • Output Restricted Double Ended Queue Input Restricted Double Ended Queue In input restricted double ended queue, the insertion operation is performed at only one end and deletion operation is performed at both the ends. Output Restricted Double Ended Queue In output restricted double ended queue, the deletion operation is performed at only one end and insertion operation is performed at both the ends. Priority Queue Priority Queue is more specialized data structure than Queue. Like ordinary queue, priority queue has same method but with a major difference. In Priority queue items are ordered by key value so that item with the lowest value of key is at front and item with the highest value of key is at rear or vice versa. So we are assigned priority to item based on its key value. Lower the value, higher the priority. Following are the principal methods of a Priority Queue. Module II-Stacks, Queues, Recursion Dr. Ganga Holi, ISE Dept., Global academy of Technology 23 Basic Operations • insert / enqueue − add an item to the rear of the queue. • remove / dequeue − remove an item from the front of the queue. There are various ways of implementing the priority queues. Double Ended Queue can be represented in various ways. • Using single array • Multiple arrays • Linked list • Heap Using single array, we can implemented priority queue as follows... Using single array #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #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);


>= 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→ 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 • What is stack? What are the operations on stack?> • What is the recursion? What are two important criteria for recursive functions? • How does rear and front work in circular queue in C language? • What are the applications of queues and stacks? • How is priority queue implemented in C? • Can we use an array to create a circular queue? • What is the application of queues in computer science? • What is the advance application of circular queue? • What is queue and a circular queue? • How does rear and


How is priority queue implemented in C? • Can we use an array to create a circular queue? • What is the application of queues in computer science? • What is the advance application of circular queue? • What is queue and a circular queue? • How does rear and front work in circular queue in C language? • What is dequeue? How to insert and delete from dequeue. • 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


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


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


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


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 – 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


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 • They are a dynamic in nature which allocates the memory when required. • Insertion and deletion operations can be easily implemented. • Stacks and queues can be easily executed. • Linked List reduces the access time. 1.1.1.2 Disadvantages of Linked Lists • The memory is wasted as pointers require extra memory for storage. • No element can be accessed randomly; it has to access each node sequentially. • Reverse Traversing is difficult in single linked list. 1.1.1.3 Applications of Linked Lists • Linked lists are used to implement stacks, queues, graphs, etc. • Linked lists let you insert elements at the beginning and end of the list. • In Linked Lists we don’t need to know the size in advance. 1.1.1.4 Types of Linked Lists • 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 • 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. • 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


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. • INFO/Link − Each Link of a linked list can store a data called an element. • Next/Ptr − Each Link of a linked list contain a link to next link called Next. • LinkedList − 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. • Linked List contains a pointer variable called first. • Each node carries a data field(s) and a pointer Field called next. • Each node is linked with its next pointer using its next pointer. • 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;


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(“deleted element is %d\n”, 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(“%d→”, 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<stdio.h> #include<stdlib.h> 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→item=data; temp→next=NULL; if(first==NULL) first=temp; else { temp→next=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→item=data; 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("%d→", cur→item); cur=cur→next; } 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→item); first=first→next; free(temp); return first; } NODE* deleterear(NODE* first) { NODE *cur, *prev; cur=first; if(first==NULL) { printf("List is Empty"); return first; } if(first→next==NULL) { printf("Deleted *** rear element=%d\n",first→item); first=NULL; free(cur); return first; } prev=NULL; while(cur→next!=NULL) { prev=cur; cur=cur→next; } prev→next=cur→next; printf("Deleted Rear element=%d\n",cur→item); 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→item=ele; nn→next=NULL; if(first==NULL) { first=nn; return first; } if(first→item >ele) { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 14 nn→next=first; first=nn; return first; } pre=first; cur=first; while(cur→item <=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; } else { cur→next=nn; } return first; } 8 Write


Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 14 nn→next=first; first=nn; return first; } pre=first; cur=first; while(cur→item <=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; } else { cur→next=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→item ==ele) { first=NULL; printf("Deleted Rear element=%d\n",cur→item); free(cur); return first; } pre=first; cur=first; while(cur→item !=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } 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→next=cur→next; } 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→item=ele; nn→next=NULL; if(first==NULL) { first=nn; return first; } if(pos==1) { nn→next=first; first=nn; return first; } pre=first; cur=first; while(count < pos && cur→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count >= pos) { pre→next=nn; nn→next=cur; } else { cur→next=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→item); first=first→next; free(cur); return first; } pre=first; cur=first; while(count != pos && cur→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count!=pos && cur-->next==NULL) { printf(" position is not found\n"); } if(count == pos) { pre→next=cur→next; printf("Element deleted %d from pos %d\n",pos, first→item); 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→",temp→item); Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 17 if(temp→next==NULL) break; temp=temp→next→next; } 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<stdio.h> #include<stdlib.h> 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→item=ele; nn-->next=NULL; if(first==NULL) { first=nn; return; } if(first→item >ele) { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 18 nn→next=first; first=nn; return; } pre=first; cur=first; while(cur→item <=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; } else { cur→next=nn; } } void display(NODE *first) { NODE *temp; temp=first; if(first==NULL) { printf("empty list\n"); return; } while(temp!=NULL) { printf("%d→",temp→item); temp=temp→next; } printf("\ndone\n"); } NODE* insertFront(NODE *revFirst,int item) { NODE *nn; nn=(NODE*)malloc(sizeof(NODE)); nn→item=item; nn→next=NULL; if(revFirst==NULL) revFirst=nn;


&& cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; } else { cur→next=nn; } } void display(NODE *first) { NODE *temp; temp=first; if(first==NULL) { printf("empty list\n"); return; } while(temp!=NULL) { printf("%d→",temp→item); temp=temp→next; } printf("\ndone\n"); } NODE* insertFront(NODE *revFirst,int item) { NODE *nn; nn=(NODE*)malloc(sizeof(NODE)); nn→item=item; nn→next=NULL; if(revFirst==NULL) revFirst=nn; else { nn→next=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→item); prev = current; current = current→next; } } NODE* reverse2() { struct node* prev = NULL; struct node* current = first; struct node* next; while (current != NULL) { next = current→next; current→next = 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<n;i++) { printf("enter ele="); scanf("%d",&ele); orderedInsert(ele); display(first); } printf("\n\n-----------\n Display LL elements\n"); display(first); printf("Display Reverse elements\n"); reverse1(); display(revFirst); printf("Display Reverse using II ,method elements\n"); reverse2(); display(newfirst); } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 20 Single Linked List with Header Node 13 Write a program to insert at front, rear, in ordered, at specified position, and delete from front, rear, ordered, element and from specified position. #include<stdio.h> #include<stdlib.h> 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→item=data; temp→next=NULL; if(head→next==NULL) { head→next=temp; head→item++; } else { temp→next=head→next; head→next=temp; head→item++; } 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→next=NULL; if(head→next==NULL) { head→next=temp; } else { cur=head→next; while(cur→next!=NULL) { cur=cur→next; } cur→next=temp; } head→item++; return ; } void deletefront() { NODE *temp; int num; temp=head→next; if(head→next==NULL) { printf("List is Empty"); return; } printf("Front element deleted =%d\n",temp-->item); head→next=temp→next; head→item--; free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=head→next; if(head→next==NULL) { printf("List is Empty"); return; } if(cur→next==NULL) { printf("Deleted *** rear element=%d\n",cur→item); head→next=NULL; head→item--; 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→next!=NULL) { prev=cur; cur=cur→next; } prev→next=cur→next; head→item--; printf("Deleted Rear element=%d\n",cur→item); free(cur); return ; } void orderedInsert(int ele) { NODE *nn, *pre, *cur, *first; nn=(NODE*)malloc(sizeof(NODE)); nn→item=ele; nn→next=NULL; first=head→next; if(first==NULL) { head→next=nn; head→item++; return; } if(first→item >ele) { nn→next=first; head→next=nn; head→item++; return; } pre=first; cur=first; while(cur→item <=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; head→item++; } else { cur→next=nn; head→item++; } } void deleteFromordered(int ele) { NODE *pre, *cur; if(head-->next==NULL) { printf("Empty list\n"); return ; } cur=head→next; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 23 if(cur→item ==ele)


} if(cur→item >ele) { pre→next=nn; nn→next=cur; head→item++; } else { cur→next=nn; head→item++; } } void deleteFromordered(int ele) { NODE *pre, *cur; if(head-->next==NULL) { printf("Empty list\n"); return ; } cur=head→next; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 23 if(cur→item ==ele) { head→next=NULL; head→item--; printf("Deleted Rear element=%d\n",cur→item); free(cur); return ; } pre=NULL; 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; } if(cur→item == ele) { pre→next=cur→next; head→item--; } return ; } void InsertAtPos(int ele, int pos) { NODE *nn, *pre, *cur; int count=1; nn=(NODE*)malloc(sizeof(NODE)); nn→item=ele; nn→next=NULL; if(head→next==NULL) { head→next=nn; head→item++; return; } if(pos==1) { nn→next=head→next; head→next=nn; head→item++; return; } pre=NULL; cur=head→next; while(count < pos && cur→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count >= pos) { pre→next=nn; nn→next=cur; } else { Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 24 cur→next=nn; } head→item++; return ; } void DeleteFromPos(int pos) { NODE *pre, *cur; int count=1; pre=NULL; cur=head-->next; if(head→next==NULL) { printf("List is Empty"); return ; } if(pos==1) { printf("Front element deleted =%d\n",cur-->item); head→next=cur→next; head→item--; free(cur); return ; } pre=NULL; cur=head→next; while(count != pos && cur→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count != pos && cur→next ==NULL) { printf("Posotion not valid\n"); return; } if(count == pos) { pre→next=cur→next; head-->item--; printf("Element deleted %d from pos %d\n",pos, cur→item); free(cur); } return ; } void display() { NODE *temp, *first; temp=first=head→next;; if(first==NULL) { printf("empty list\n"); return; } while(temp!=NULL) { printf("%d→",temp→item); temp=temp→next; 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→item); } int main() { int i,ele, val, pos; head=(NODE*) malloc(sizeof(NODE)); head→next=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<stdio.h> #include<stdlib.h> 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→item=data; Temp→next=NULL; if(first==NULL) { first=temp; first→next=first; } else { cur=first; while(cur→next!=first) { cur=cur→next; } temp→next=first; first=temp; cur→next=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→item=data; temp→next=NULL; if(first==NULL) { first=temp; first→next=first; } else { cur=first; while(cur→next!=first) { cur=cur→next; } cur→next=temp; temp→next=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;


temp→next=NULL; if(first==NULL) { first=temp; first→next=first; } else { cur=first; while(cur→next!=first) { cur=cur→next; } cur→next=temp; temp→next=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-→", cur→item); cur=cur→next; } printf("%d-→", cur→item); 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→item); last=first; while(last→next!=first) { last=last→next; } first=first→next; last→next=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→next==NULL) { printf("Deleted *** rear element=%d\n",first→item); 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→next!=first) { prev=cur; cur=cur→next; } prev→next=cur→next; printf("Deleted Rear element=%d\n",cur→item); free(cur); return first; } NODE* orderedInsert(NODE* first, int ele) { NODE *nn, *pre, *cur, *last; nn=(NODE*)malloc(sizeof(NODE)); nn→item=ele; nn→next=NULL; if(first==NULL) { first=nn; first→next=first; first; } if(first→item >ele) { nn→next=first; last=first; while(last→next!=first) { last=last→next; } first=nn; last→next=first; return first; } pre=first; cur=first; while(cur→item <=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; } else { cur→next=nn; nn→next=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→item ==ele) { first=first→next; printf("Deleted Rear element=%d\n",cur→item); last=first; while(last→next!=first) { last=last→next; } last→next=first; free(cur); return first; } pre=first; cur=first; while(cur→item !=ele && cur→next !=first) { pre=cur; cur=cur→next; } if(cur→item !=ele && cur→next ==first) { printf("Element not found\n"); return first; } pre→next=cur→next; 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→item=ele; nn→next=NULL; if(first==NULL) { first=nn; first→next=first; return first; } if(pos==1) { nn→next=first; last=first; while(last→next!=first) { last=last→next; } first=nn; last→next=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→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count >= pos) { pre→next=nn; nn→next=cur; } else { cur→next=nn; nn→next=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→item); last=first; while(last→next!=first) { last=last→next; } first=first→next; last→next=first; free(cur); return first; ; } pre=NULL; cur=first; while(count != pos && cur→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count!=pos && cur→next==NULL) { printf(" position is not found\n"); } if(count == pos) { pre→next=cur→next; printf("Element deleted %d from pos %d\n",pos, first→item); 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<n;i++) { printf("\n item


deleted %d from pos %d\n",pos, first→item); 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<n;i++) { printf("\n item value="); scanf("%d", &val); first=insertrear(first,val); //first=insertfront(first,val); //first=orderedInsert(first,val); display(first); } printf("\n Linked List is \n"); display(first); first=deletefront(first); display(first); first=deleterear(first); display(first); printf("\n item value and position="); scanf("%d%d", &val,&pos); first=InsertAtPos(first,val,pos); display(first); printf("\n Enter value to delete ="); scanf("%d", &val); first=deleteFromordered(first, val); display(first); printf("\n Enter posotion from which ele to delete ="); scanf("%d", &pos); first=DeleteFromPos(first, pos); display(first); return 0; } 15 Write a program to insert and delete from circular single linked list with head node. #include<stdio.h> #include<stdlib.h> 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→item=data; temp→next=NULL; if(head→next==NULL) { printf(" First element\n\n"); head→next=temp; temp→next=temp; head→item++; } else { temp→next=head→next; last=head→next; while(last→next!=head→next) { last=last→next; } head→next=temp; last→next=head→next; head→item++; } return; } void insertrear(int data) { NODE *temp, *cur; temp=(NODE*)malloc(sizeof(NODE)); if(temp==NULL) { printf("insufficient memory\n"); return ; } temp→item=data; temp→next=NULL; if(head→next==NULL) { head→next=temp; temp→next=temp; Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 33 } else { cur=head→next; while(cur→next!=head→next) { cur=cur→next; } cur→next=temp; temp→next=head→next; } head→item++; return ; } void deletefront() { NODE *temp, *last; int num; temp=head-->next; if(head→next==NULL) { printf("List is Empty"); return; } printf("Front element deleted =%d\n",temp→item); last=head→next; while(last→next!=head→next) { last=last→next; } head→next=temp→next; last→next=head→next; head-->item--; free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=head-->next; if(head-->next==NULL) { printf("List is Empty"); return; } if(cur→next==NULL) { printf("Deleted *** rear element=%d\n",cur→item); head→next=NULL; head→item--; 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→next!=NULL) { prev=cur; cur=cur→next; } prev→next=cur→next; head→item--; printf("Deleted Rear element=%d\n",cur→item); free(cur); return ; } void orderedInsert(int ele) { NODE *nn, *pre, *cur, *last; nn=(NODE*)malloc(sizeof(NODE)); nn→item=ele; nn→next=NULL; cur=head→next; if(head→next==NULL) { head→next=nn; nn→next=nn; head→item++; return; } if(cur→item >ele) { nn→next=cur; last=cur; while(last→next!=head-->next) { last=last→next; } head→next=nn; last→next=head→next; head→item++; return; } pre=NULL; cur=head→next; while(cur→item <=ele && cur→next !=head→next) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; head→item++; } else { cur→next=nn; nn→next=head→next; head→item++; } } 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→next==NULL) { printf("Empty list\n"); return ; } cur=head→next; if(cur→item ==ele) { if(cur→next==head→next) { head→next=NULL; } else { last=head→next; while(last→next!=head→next) { last=last→next; } head→next=cur→next; last→next=head→next; } printf("Deleted Rear element=%d\n",cur→item); free(cur); head→item--; return ; } pre=NULL; while(cur→item !=ele && cur→next !=head→next) { pre=cur; cur=cur→next; } if(cur→item !=ele && cur→next ==NULL) { printf(" Element not found\n"); return; } if(cur→item == ele) { pre→next=cur→next; free(cur); head→item--; } return ; } void InsertAtPos(int ele, int


last=last→next; } head→next=cur→next; last→next=head→next; } printf("Deleted Rear element=%d\n",cur→item); free(cur); head→item--; return ; } pre=NULL; while(cur→item !=ele && cur→next !=head→next) { pre=cur; cur=cur→next; } if(cur→item !=ele && cur→next ==NULL) { printf(" Element not found\n"); return; } if(cur→item == ele) { pre→next=cur→next; free(cur); head→item--; } return ; } void InsertAtPos(int ele, int pos) { NODE *nn, *pre, *cur, *last; int count=1; nn=(NODE*)malloc(sizeof(NODE)); nn→item=ele; nn→next=NULL; if(head→next==NULL) { head→next=nn; nn→next=nn; head→item++; return; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 36 if(pos==1) { nn→next=head→next; last=head→next; while(last→next!=head→next) { last=last→next; } head→next=nn; last→next=head→next; head→item++; return; } pre=NULL; cur=head→next; while(count < pos && cur→next !=head→next) { pre=cur; count++; cur=cur→next; } if(count >= pos) { pre→next=nn; nn→next=cur; } else { cur→next=nn; nn→next=head→next; } head→item++; return ; } void DeleteFromPos(int pos) { NODE *pre, *cur, *last; int count=1; pre=NULL; cur=head→next; if(head→next==NULL) { printf("List is Empty"); return ; } if(pos==1) { printf("Front element deleted =%d\n",cur→item); last=head→next; while(last→next!=head→next) { last=last→next; } head→next=cur→next; last→next=head→next; head→item--; 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→next; while(count != pos && cur→next !=NULL) { pre=cur; count++; cur=cur→next; } if(count != pos && cur→next ==NULL) { printf("Posotion not valid\n"); return; } if(count == pos) { pre→next=cur→next; head→item--; printf("Element deleted %d from pos %d\n",pos, cur→item); free(cur); } return ; } void display() { NODE *temp; temp=head→next; if(head→next==NULL) { printf("empty list\n"); return; } while(temp→next!=head→next) { printf("%d→",temp→item); temp=temp→next; } printf("%d→",temp→item); printf("\n \nDone total nodes=%d\n", head→item); } int main() { int i,ele, val, pos,n; head=(NODE*) malloc(sizeof(NODE)); head→next=NULL; head→item=0; printf("enter n="); scanf("%d",&n); printf("enter %d elements=",n); for(i=0;i<n;i++) { printf("enter ele="); scanf("%d",&val); //insertrear(val); //insertfront(val); orderedInsert(val); display(); Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 38 } 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(); } 16 Write a program to insert & delete from both ends with first & last pointer. #include<stdio.h> #include<stdlib.h> 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→item=data; Temp→next=NULL; if(*first==NULL) { *first=temp; *last=temp; } else { temp→next=*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→item=data; temp→next=NULL; if(*first==NULL) { *first=temp; *last=temp; } else { cur=*last; cur→next=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→", cur->item); cur=cur→next; } 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


void display(NODE* first) { NODE *cur; if(first==NULL) { printf(" Empty List\n"); return; } cur=first; while(cur!=NULL) { printf("%d→", cur->item); cur=cur→next; } 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→item); *first=temp→next; free(temp); return ; } NODE* deleterear(NODE** first, NODE **last) { NODE *cur, *prev; cur=*first; if(*first==NULL) { printf("List is Empty"); return; } if(cur→:next==NULL) { printf("Deleted *** rear element=%d\n",cur→item); *first=NULL; free(cur); return ; } prev=NULL; while(cur→next!=NULL) { prev=cur; cur=cur→next; } Prev→next=cur→next; printf("Deleted Rear element=%d\n",cur→item); free(cur); return; } NODE* orderedInsert(NODE** first, NODE **last, int ele) { NODE *nn, *pre, *cur; nn=(NODE*)malloc(sizeof(NODE)); nn→item=ele; nn→next=NULL; cur=*first; if(*first==NULL) { *first=nn; return ; } if(cur→item >ele) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 41 { nn→next=*first; *first=nn; return ; } pre=NULL; cur=*first; while(cur→item <=ele && cur→next !=NULL) { pre=cur; cur=cur→next; } if(cur→item >ele) { pre→next=nn; nn→next=cur; } else { cur→next=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<n;i++) { printf("\n item value="); scanf("%d", &val); //first=insertfront(first,val); orderedInsert(&first,&last,val); display(first); } printf("\n Linked List is \n"); display(first); deletefront(&first,&last); display(first); deleterear(&first,&last); display(first); return 0; } Doubly Linked List Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 42 17 Write a progrm to insert, delete from both ends and insert into ordered DLL and delete from Ordered DLL. #include<stdio.h> #include<stdlib.h> #include<string.h> 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→item=ele; temp→next=NULL; if(first==NULL) { first=temp; return; } cur=first; prev=NULL; while(cur→next != NULL) { prev=cur; cur=cur→next; } cur→next =temp; tem→prev=prev; return ; } void insertfront(int ele) { NODE *temp; temp= (NODE *)malloc(sizeof(NODE)); temp→item=ele; temp→next=NULL; if (first== NULL) { first=temp; } else { temp→next=first; first→prev=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→next==NULL) first=NULL; else { first=first→next; First→prev=NULL; } printf(" Element=%d\n", temp→item); free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=first; prev=NULL; if(first==NULL) { printf(" List is Empty \n");return ; } if(first→next==NULL) { first=NULL; } else { while(cur→next!=NULL) { prev=cur; cur=cur→next; } prev→next=NULL; } printf(" Element=%d\n", cur→item); 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-→",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(first==NULL) { first=nn; return; } if(first→item >ele) { nn→next=first; first→prev=nn; first=nn; return;


Head, ISE Dept., Global Academy of Technology 44 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(first==NULL) { first=nn; return; } if(first→item >ele) { nn→next=first; first→prev=nn; first=nn; return; } pre=NULL; cur=first; 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; } } void deleteOrdered(int ele) { NODE *pre, *cur; if(first==NULL) { printf("Empty list\n"); return first; } cur=first; if(first→item ==ele) Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 45 { first=first→next; if(first!=NULL) first→prev=NULL; printf("Deleted Rear element=%d\n",cur→item); free(cur); return first; } pre=NULL; cur=first; 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 first; } pre→next=cur→next; 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<stdio.h> #include<stdlib.h> #include<string.h> 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.,


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 – 43). #include<stdio.h> #include<stdlib.h> 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)


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<ln1;i++) { printf("\n Enter Coef & power="); scanf("%d%d", &c,&p); first=insertrear(first,c,p); //display(first); } display(first); printf(" Enter no of nodes for second List="); scanf("%d", &ln2); for(i=0;i<ln2;i++) { printf("\n Enter Coef & power="); scanf("%d%d", &c,&p); second=insertrear(second,c,p); //display(second); } printf("\n Polynomial addition using Linked List is \n"); third=polyadd(first, second,third); display(third); printf("Enter the value of x="); scanf("%d",&x); evaluate(third,x); return 0; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 53 20 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. #include<stdio.h> #include<stdlib.h> 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<ln1;i++) { printf("\n Enter Coef & power="); scanf("%d%d", &c,&p); first=insertrear(first,c,p); //display(first); } display(first); printf(" Enter no of nodes for second List="); scanf("%d", &ln2); for(i=0;i<ln2;i++) { printf("\n Enter Coef & power="); scanf("%d%d", &c,&p); second=insertrear(second,c,p); //display(second); } printf("\n Polynomial addition using Linked List is \n"); third=polyadd(first, second,third); display(third); return 0; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 56 Questions on Linked List


&ln2); for(i=0;i<ln2;i++) { printf("\n Enter Coef & power="); scanf("%d%d", &c,&p); second=insertrear(second,c,p); //display(second); } printf("\n Polynomial addition using Linked List is \n"); third=polyadd(first, second,third); display(third); return 0; } Module III Notes/Programs on Linked List Dr. Ganga Holi, Professor & Head, ISE Dept., Global Academy of Technology 56 Questions on Linked List What is list? How list can be represented in memory. What is Linked List? Explain different types of Linked Lists. What are the difference between linked list and arrays? Mention the advantages and disadvantages of arrays and linked list. Explain dynamic memory allocation techniques which are used to allocate memory. What is heap? Why do you need double linked lists? Why do you want circular linked list and header linked lists.