Data Structures
Data Structures
Aim:
Write recursive programme which computes the nth Fibonacci number, for appropriate values of n.
Analyze behavior of the programme Obtain the frequency count of the statement for various
values of n.
Description: The Fibonacci numbers or Fibonacci series are the numbers in the
following integer sequence: 0,1,1,2,3,5,8,13,21,…. .By definition, the first two numbers in the
Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence
relation Fn= Fn-1 + Fn-2
Algorithm:
Input: Read n value
th
Output: Prints the n Fibonacci term
Step1: Start
th
Step2: Read n value for computing n term in Fibonacci series
Step5: End
Fibonacci(n)
// Algorithm Fibonacci computes the nth Fibonacci number, for appropriate values of n.
Step1: If n = 0 then go to step2 else go to step3
Step2: return 0
Step3: If n = 1 then go to step4 else go to step5
Step4: return 1
Step5: return(Fibonacci (n-1) + Fibonacci (n-2))
Sample Input:
Fibonacci number upto 8 is 11
Observed Output:
Fibonacci Number Computation
For which term you want to compute the Fibonacci number 9
Fibonacci Number of 9 is 19
Viva questions:
Aim:
Write recursive and non recursive C programme for calculation of Factorial of an integer
Description:
A recursive function defines values of the functions for some inputs in terms of the values of
the same function for other inputs. Simply a recursion function can be defined as a function call to
itself. The recursion concept was implemented using the data structure called
STACKS.The factorial of a non-negative integer n, denoted by n! . It is the product of all positive
integers less than or equal to n. For example, 5! =5*4*3*2*1=120
Algorithm:
1. Start.
2. Get the number nto which Factorial value is to be calculated.
3. Print Menu 1. Recursive function 2. Non-recursive function
4. If choice=1 then Call Factorial(n).
5. Else if choice=2 then Call NonRecFactorial(n)
6. Printf factorial Number
7. Stop
Factorial(n) 1.Start
2. If n= 0 or 1 then fact=1
3. else fact= n* factorial(n-1)
4. return(fact)
NonRecFactorial(n)
1.Start
2. for i=1 to i<=n do
3. fact=fact*i;
4. return (fact)
Sample Input:
Factorial of 5 is 120
Observed Output:
Output1:
Factorial of recursion and non recursion
Enter the number 6
Enter the choice 1
Recursion Factorial of 6 is 720
Output 2:
Factorial of recursion and non recursion
Enter the number 7
Enter the choice 2
Recursion Factorial of 7 is 5040
Aim:
Description:
In mathematics, the greatest common divisor (GCD), also known as the greatest common
factor (GCF), or highest common factor (HCF), of two or more non-zero integers, is the largest
positive integer that divides the numbers without a remainder
For example, the GCD of 8 and 12 is 4.
Algorithm:
/* GCD recursive and Non-Recursive */
Input: integer a, b
Output: GCD of a, b
1. Start.
2. Get two numbersm, n for which GCD is to be calculated.
3. Print Menu 1. Recursive function 2. Non-recursive function
4. If choice=1 then Call GCD(m,n).
5. Else if choice=2 then Call NonRec GCD(m,n).
6. Print GCD
7. Stop.
GCD(int a, int b)
1.begin
5. return a
6. g= gcd_rec (b, a mod b)
7. return g
Sample Input:
GCD of 16 and 4 is: 4
Observed Output:
Computing GCD of TWO numbers
Enter two numbers 36 54
The Recursion GCD of 36 and 54 is 18
The Non-Recursion GCD of 36 and 54 is 18
Write recursive C programme for Towers of Hanoi: N disks are to be transferred from peg S to peg
D with Peg I as the intermediate peg.
Description:
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number
of disks of different sizes which should be transferred from soruce to destination using the
intermediate rod. The puzzle starts with the disks in a neat stack in ascending order of size on one
rod, the smallest at the top, thus making a conical shape.The objective of the puzzle is to move the
entire stack to another rod, obeying the following rules:
TOH(N, S, I, D)
1.begin
2. if n = 1 then
3. Transfer disk from S to D and stop
4. else
5. transfer N-1 disks from peg S to peg I with peg D as the intermediate peg
6. Call TOH(N-1, S, D, I)
7. Transfer disk from S to D
8. transfer N-1 disks from peg I to peg D with peg S as the intermediate peg
9. Call TOH(N-1, I, S, D);
10.end
Sample Input:
ENTER NUMBER OF DISKS:3
Move diskA from S to D
Move diskB from S to I
Move diskA from D to I
Move diskC from S to D
Move diskA from I to S
Move diskB from I to D
Move diskA from S to D
Observed Output:
TOWERS OF HANOI
Enter the number of disks :3
Move disk-1 from S to D
Move disk-2 from S to I
Move disk-1 from D to I
Move disk-3 from S to D
Write C programs that use both recursive and non recursive functions to perform Linear search for a
Key value in a given list.
Description:
The linear search is most simple searching method. It does not expect the list to be sorted.
The key which is to be searched is compared with each element of the list one by one. If a match
exists, the search is terminated. If the end of list is reached it means that the search has failed and
key has no matching in the list.
Algorithm:
1.Start
2. Read the array size ‗n‘
3. Read elements into array ‗L‘
4. Read the key to be searched in array ‗K‘
5. Print Menu 1. Recursive function 2. Non-recursive function
6. Read the choice
7. if choice=1 then call pos = LINEAR_SEARCH_REC(L, n, K)
8. else if choice=2 then call pos = LINEAR_SEARCH_NONREC(L, n, K)
9. ifpos< 1 then print ‗ key not found‘
10. else print ‗key found in index position ‘, i
11. Stop
LINEAR_SEARCH_NONREC(L, n, K) 1.i = 0
2. while (( i < n) and (K != L[i])) do
3. i = i + 1;
4. end while
5. if ( K = L[i]) then print (― KEY found‖) and return (i)
LINEAR_SEARCH_REC(L, n, K)
Sample Input:
Key : 2
2 is found
Observed Output:
EX. NO: 3(B) BINARY SEARCH USING RECURSIVE & NON- RECURSIVE
FUNCTIONS
Aim:
Write C programs that use both recursive and non recursive functions to perform Binary search for
a Key value in a given list.
Description:
Binary search is a vast improvement over the sequential (Linear) search. For binary search
to work, the item in the list must be in a sorted order. The approach employed in the binary search is
divide and conquer. In binary search the list is divided into two half’s based on the MID value, and
the key is compared with the mid element. If it is successful then it returns the mid value, if the key
value is not found at mid then the search will proceed in any one of the half’s based on whether the
key element is greater or lesser than the mid element. If the list to be sorted for a specific item is not
sorted, binary search fails. The Mid value can be calculated by the formula:
MID= (HIGH+LOW)/2
Algorithm:
1.Start
2. Read the array size ‗n‘
3. Read elements into array ‗L‘
4. Read the key to be searched in array ‗K‘
5. low=0, high = N – 1
6. Print Menu 1. Recursive function 2. Non-recursive function
7. Read the choice
8. if choice=1 then call to the function pos = BINARY_SEARCH_REC(L, low, high, K)
9. else if choice=2 then pos = BINARY_SEARCH_NONREC(L, low, high, K)
10. ifpos< 1 then print ‗ key not found‘
11. else print ‗key found in index position ‘,i
12. Stop
Sample Input:
Enter Key: 26
Observed Output:
Write C programs that use both recursive and non recursive functions to perform Fibonacci search
for a Key value in a given list.
Description:
A possible improvement in binary search is not to use the middle element at each step, but to
guess more precisely where the key being sought falls within the current interval of interest. This
improved version is called Fibonacci search. Instead of splitting the array in the middle, this
implementation splits the array corresponding to the Fibonacci numbers, which are defined in the
following manner:
F0 = 0, F1 = 1
Fn = Fn-1+Fn-2 for n>=2.
Algorithm:
1.Start
2. Read the array size ‗n‘
3. Read elements into array ‗L‘
4. Read the key to be searched in array ‗K‘
5. low=0, high = N – 1
6. Print Menu 1. Recursive function 2. Non-recursive function
7. Read the choice
8. if choice=1 then call to the function pos = FIBONACCI_SEARCH _REC(L, n, K)
9. else if choice=2 then pos = FIBONACCI_SEARCH _NONREC(L, n, K)
10. if pos< 1 then print ‗ key not found‘
11. else print ‗key found in index position ‘,i
12. Stop
FIBONACCI_SEARCH _NONREC(L, n, K)
/*L[1:n] is a linear ordered (non-decreasing) list of data elements. n is such that k+1>(n+1).Also
p=Fk-1;
q=Fk-2; r=Fk-3;
m=(n+1)-(p+q);
if (k>L[p]) then
p=p+m;
found =false;
while ( (p=!0) and (not found )) do
case: k=L[p]:
{
print (―key found‖); /* key found */
found =true;
}
Case:k<L[p]:
if (r=0) then p=0
else
{
p=p-r; t=q; q=r; r=t-r;
}
Case: k> L[p]:
if (q=1) then p=0
else
{
p=p+r; q=q-r; r=r-q
}
end case
end while
if(found=false) then print (―key not found‖);
end FIBONACCI_SEARCH_NONREC.
FIBONACCI_SEARCH_REC (L,n,k)
/*L[1:n] is a linear ordered (non-decreasing) list of data elements. n is such that k+1>(n+1).Also
p=Fk-1;
q=Fk-2; r=Fk-3;
m=(n+1)-(p+q);
if (k>L[p]) then p=p+m;
call pos=Fibsearch(L,key,p,q,r);
returnpos;
end FIBONACCI_SEARCH_REC.
Sample Input:
45 found at position 4
Observed Output:
Viva questions:
Aim:
Write C programs that implement Bubble sort, to sort a given list of integers in ascending order.
Description:
Bubble sort is the simplest and oldest sorting technique. This method takes two elements at
a time. It compares these two elements. If first elements is less than second one, they are left un
disturbed. If the first element is greater then second one then they are swapped. The continues with
the next two elements goes and ends when all the elements are sorted. But bubble sort is an
inefficient algorithm. The order of bubble sort algorithm is O(n2).
Algorithm:
/* Bubble_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
1.Start
2. Read the size of the array ‗n‘
3. Read the elements of the array ‗ L‘
4. call BUBBLE_SORT(L,n)
5. print array ‗L‘
6. Stop
BUBBLE_SORT(L,n)
Sample Input:
Enter the array size: 3
Enter elements: 54 67 12
The sorted array is: 12 54 67
Observed Output:
Write C programs that implement Quick sort, to sort a given list of integers in ascending order
Description:
This method is invented by hoare, considered to be fast method to sort the elements. The
method is also called partition exchange sorting. The method is based on divide and conquer
technique. i.e., the entire list is divided into various partitions and sorting is applied again and again
on the partition.
In this method the list is divided into two based on an element called pivot element.
Usually the first element is considered to be the pivot element. Now move the pivot element to its
correct position in the list. The elements to the left and pivot element are less that this while the
elements to the right of pivot are greater than the pivot. The process is reapplied to each of these
partitions till we got the sorted list of elements.
Algorithm:
/* Quick _ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
1.Start
2. Read the size of the array ‗n‘
3. Read the elements of the array ‗ L‘
4. call QUICK_SORT(L,n)
/* L [first: last] is the unordered list of elements to be quick sorted. The call to the to sort the list
L [1: n] would be Quick _ SORT (L, 1, n) */
if (first < last) then
{
PARTITION (L, first, last, loc) ; /* partition the list into two sub lists at loc
*/ QUICK_SORT (L, first, loc-1); /* quick sort the sub list L[first, loc-1] */
QUICK_SORT (L, loc+1, last); /* quick sort the sub list L[Loc+1, last] */
}
end QUICK_SORT.
PARTITION(L,last,loc)
/* L[first :last] is the list to be participated. Loc is the position where the pivot element finally
settles down */
Left=first
right=last+1;
pivot_elt=L[first]; /* set the pivot element to the first element in list L */
while(left<right) do
repeat
left=left+1;
until L[left]>=pivot_elt;
repeat
right=right-1;
until L[right]<=pivot_elt;
if(left<right) then swap(L[left],L[right]);
/* arrows face each other */
end
Loc=right
Swap(L[first],L[right]);
/* arrows have crossed each other – exchange pivot element L[first] with L[right] */
end PARTITION
Sample Input:
Enter the array size: 3
Enter elements: 54 67 12
The sorted array is: 12 54 67
Observed Output:
Aim:
Write C programs that implement Insertion sort, to sort a given list of integers in ascending order
Description: Insertion sort is similar to playing cards. To sort the cards in your hand you extract a
card shift the remaining cards and then insert the extracted card in its correct place. The efficiency of
insertion sort is O(n2).
Algorithm:
/* Insertion_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
1.Start
2. Read the size of the array ‗n‘
3. Read the elements of the array ‗ L‘
4. call INSERTION _SORT (L,n)
5. print array ‗L‘
6. Stop0
INSERTION_SORT (L, n)
/* L (1: n) is an unordered list of data elements to be sorted in the ascending order */
for i=2 to n do /* n-1 passes*/
Key = L[i]; /* key is the key to be inserted and position its location in the unordered list*/
position = i;
/* compare key with its sorted sub list of predecessors for insertion at the appropriate
position */
While((position > 1) and (L [position –1] > Key) do
L[position] = L [position-1];
Sample Input:
Enter the range of array:5
Enter elements into array:56 23 34 12 8
The sorted order is: 8 12 23 34 56
Observed Output:
Viva questions:
1. What is sorting.
2. In to types the sorting techniques are classified
3. Name some sorting algorithms
4. What is the best case of Bubble sort
5. What is the worst case of Bubble sort
10. What are the best, average and worst case of quick sort. Ans:
11. What are the steps in quick sort algorithm
Write C programs that implement heap sort, to sort a given list of integers in ascending order
Description:
Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part
of the selection sort family. Heapsort is a two step algorithm.
The first step is to build a heap out of data. The second step begins with removing the largest
element from the heap . We insert the removed element into the sorted array. For the first element
this would be the position of n-1 of the array. Next we reconstruct the heap and remove the next
largest item, and insert it into the array. After we have removed all the objects from the heap, we
have a sorted array. We can vary the direction of the sorted elements by choosing a min-heap or
max-heap in step one.
Algorithm:
/* Heap_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
1.Start
2. Read the size of the array ‗n‘
3. Read the elements of the array ‗ L‘
4. call HEAP_SORT(L,n)
5. print array ‗L‘
6. Stop
HEAP_SORT (L, n)
/* L [1: n] is the unordered list to be sorted. The output list is returned in L itself */
CONSTRUCT_HEAP (L, n); /* construct the initial heap out of L[1:n] */
BUILD_TREE (L, n); /* output root node and reconstruct heap */
end HEAP_SORT.
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE
29
DS LAB MANUAL
BUILD_TREE (L, n)
for end _node _index = n to 2 step-1 do
{
swap(L[1],L[end _node _index]; /* swap root node with the largest */
RECONSTRUCT_HEAP (L, end_ node_ index); /* for reconstructing heap */
}
end BUILD_TREE.
CONSTRUCT_HEAP (L, n)
/* L[1 : n] is a list to be constructed into a heap */
Sample Input:
Observed Output:
Write C programs that implement radix sort, to sort a given list of integers in ascending order
Description:
Radix sort is one of the linear sorting algorithms for integers. It functions by sorting the input
numbers on each digit, for each of the digits in the numbers. Here the numbers are sorted on the
least-significant digit first, followed by the second-least significant digit and so on till the most
significant digit.
The Time Complexity of Radix sort is O(n).
Algorithm:
/* Radix_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
1.Start
2. Read the size of the array ‗n‘ and number of digits ‗d‘
3. Read the elements of the array ‗ L‘
4. call radixsort( L, n, 10, d )
5. print array ‗L‘
6. Stop
radixsort( L, n, r, d )
*
/* radix sort sorts a list L of n keys, each comprising d digits with radix r */
Initialize each of the Q[0:r-1] linked queues representing the bins to be empty;
For i = d to 1 step -1 /* for each of the d passes over the list */
Sort the list L of n keys Ki=k1k2k3…..kd based on the digit i, inserting each of the keys K into
/* distribute the keys into Q [ 0 : (r-`) ] based on the radix value of the digits */
Delete the keys from the queues Q [ 0: r-1 ] in order, and append the elements to the output list L;
end;
Return ( L );
end radixsort.
Sample Input:
Enter the number of elements: 6
Enter elements: 12 1 98 23 65 34
The Sorted array is 1 12 23 34 65 98
Observed Output:
Write C programs that implement merge sort, to sort a given list of integers in ascending order
Description:
The sorting algorithm Merge sort produces a sorted sequence by sorting its two halves
and merging them. With a time complexity of O(nlog(n)) merge sort is optimal. Similar to the
quick sort, the merge sort algorithm is based on a divide and conquer strategy first, the sequence to
be sorted is decomposed into two halves (Divide). Each half is sorted independently (Conquer).
Then the two sorted halves are merged to a sequence
Algorithm:
/* Merge_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
1.Start
2. Read the size of the array ‗n‘
3. Read the elements of the array ‗ L‘
4. call MERGE _SORT(L,1,n)
5. print array ‗L‘
6. Stop
first1 = first;
last1 =mid;
first2 = mid +1;
last2 = last; /* set the beginning and the ending indexes of the two lists into the appropriate
variables* /
i=first; /* i is the index variable for the temporary output list tem */
/* begin air wise comparisons of elements from the two lists */
While (first1<=last1) and (first2<=last2) do
case: X[first1]<X[first2]:
{
temp[i]=X[first1];
first1= first1+1;
i=i+1;
}
Case : X[first1]>X[first2]:
{ {temp[i]=X[first2];
first2=first2+1 ;
i=i+2; }
temp[i]=X[first1];
first1=first1+1;
i=i+1;
end
/* copy list temp to list x */
for j=first to last do
X[j]=temp[j]
end
end MERGE.
MERGE (a, first, mid, last); */ merge the two sub lists a [first, mid] and a[mid+1, last] */
}
end MERGE SORT.
Sample Input:
Enter the size of array: 4
Enter the elements: 15 4 23 2
The sorted array is: 2 4 15 23
Observed Output:
Viva questions:
1. What is sorting?
2. Differentiate between sorting and searching.
3. What is a pass?
4. What is worst case and average case complexities of heap sort?
5. What are the best, worst case and average case complexities of radix sort?
6. What is best case complexity of merge sort?
7. What is worst case and average case complexities of merge sort?
Aim:
Description:
Stack is a linear data structure where it restricts operations to only one end.
That end is called as “TOP”. Stack works on the principle of “last in first out” (LIFO). Operations
to insert an element are stack is called “PUSH”. And deleting an element from stack is called
“POP”.
Algorithm:
/*Implementation of push operation on a stack */
PUSH(STACK, n, top, item)
if (top = n) then STACK_FULL;
else
{
top = top + 1;
STACK[top] = item; /* store item as top element of STACK */
}
end PUSH
Display() if top = -1
then
print ‗ Stack is empty‘
else
{
i=0;
while(top>0) do
print ‗stack[i];
i++;
end while.
}
end Display.
Sample Input:
Menu
1.push
2.pop
Enter your choice 1
Enter the element to insert 50
Do you wish to continue press y for yes and n for no: y
Menu
1.push
2.pop
Enter your choice 1
Enter the element to insert 20
Do you wish to continue press y for yes and for no:n
Stack elements are : 20 50
Observed Output:
Aim:
Write C programs that implement stack (its operations) using Linked list
Description:
The major problem with the stack using array is, it works only for fixed amount of numbers
of data values. That means the amount of data must be specified at the beginning of the
implementation itself. Stack implemented using array is not suitable, when we don’t know the size
of the data which we are going to use. A stack data structure can be implemented by using linked list
data structure. The stack implemented using linked list can work for unlimited number of values.
That means the stack implemented using linked list can work for variable size of data. So there is no
need to fix the size at the beginning of implementation.
Algorithm:
Algorithm: Push item ITEM into a linked stack S with top pointer TOP
PUSH_LINKSTACK (TOP, ITEM)
/* Insert ITEM into stack */
Call GETNODE(X)
DATA(X) = ITEM /*frame node for ITEM */
LINK(X) = TOP /* insert node X into stack */
TOP = X /* reset TOP pointer */
end PUSH_LINKSTACK.
Algorithm: Pop from a linked stack S and output the element through ITEM
POP_LINKSTACK(TOP, ITEM)
/* pop element from stack and set ITEM to the element */
if (TOP = 0) then call LINKSTACK_EMPTY
call RETURN(TEMP) ;
end POP_LINKSTACK.
Sample Input:
Linked stack
1. Push
2. Pop
3. Display
Enter your choice 1
Observed Output:
Viva questions:
1. What is stack?
2. What is the difference between a Stack and an Array?.
3. Give real time and system examples of stack?
4. What is meant by push and pop?
5. When overflow will occur in stack?
6.. What is the significance of top pointer?
7. State different applications of stack.
Aim:
Write a C program that uses Stack operations to convert infix expression into postfix expression
Description:
In normal algebra we use the Infix notation like a+b*c. The corresponding Postfix expression
will look like abc*+.
Algorithm:
(a) Repeatedly pop from stack and add to P (on the top of stack until a left parenthesis is
encountered.
(b) Remove the left parenthesis. [Do not add the left parenthesis to P.]
7. Exit.
Sample Input:
Read the infix expression a+b*c-d
Given infix expression: a+b*c-d
Postfix expression: abc*c+d-
Observed Output:
Description:
Queue is a linear data structure where operations are done at two ends. The end where
element is intersected is called as “REAR”. The end where element is deleted is called as “FRONT”.
Queue works on the principle of “FIRST IN FIRST OUT”. Operations to insert an element in queue
are called ENQUEUE. And deleting an element from queue is called “DEQUEUE”
Algorithm:
/*Implementation of Display*/
Display() if front = -
1 then
print ‗Queue is empty‘
else
{
i=front+1;
while(i< rear) do
print queue[i]
i++;
end while
end Display.
Sample Input:
Menu
1. Insert
2. Delete
Enter your choice 1
Enter the element to insert 23
Do you wish to continue press Y for yes n for no: Y
Menu
1. Insert
2. Delete
Enter your choice 1
Enter the element to insert 18
Do you wish to continue press Y for yes n for no: Y
Menu
1. Insert
2. Delete
Enter your choice 2
Element deleted is 23
Do you wish to continue press Y for yes n for no: N
The element is queue are 18
Observed Output:
Aim:
Write C programs that implement Queue (its operations) using linked lists
Descritpion:
Queue is a particular kind of abstract data type or collection in which the entities in the
collection are kept in order and the principal (or only) operations on the collection are the addition of
entities to the rear terminal position, known as enqueue, and removal of entities from the front
terminal position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data
structure. Linked list is a data structure consisting of a group of nodes which together represent a
sequence. Here we need to apply the application of linkedlist to perform basic operations of queue.
Algorithm:
Algorithm: Push item ITEM into a linear queue Q with FRONT and REAR as the front and rear
pointer to the queue
INSERT_LINKQUEUE(FRONT,REAR,ITEM) Call
GETNODE(X);
DATA(X)= ITEM;
LINK(X)= NIL; /* Node with ITEM is ready to be inserted into Q */
if (FRONT = 0) then FRONT = REAR = X;
/* If Q is empty then ITEM is the first element in the queue Q */
else {LINK(REAR) = X;
REAR = X
}
end INSERT_LINKQUEUE.
Algorithm: Delete element from the linked queue Q through ITEM with FRONT and REAR as
the front and rear pointers
DELETE_LINKQUEUE (FRONT,ITEM)
if (FRONT = 0) then call LINKQUEUE_EMPTY;
Sample Input:
Linked queue
1. Enqueue
2. Dequeue
3. Display
Enter your choice: 1
Enter the item 48
Linked queue
1. Enqueue
2. Dequeue
3. Display
Enter your choice: 1
Enter the item 8
Linked queue
1. Enqueue
2. Dequeue
3. Display
Enter your choice: 2
Deleted element is 48
Linked queue
1. Enqueue
2. Dequeue
3. Display
Enter your choice 3
The elements are 8
Observed Output:
Viva questions:
Aim:
a) Write a C program that uses functions to create a singly linked list
b) Write a C program that uses functions to perform insertion operation on a singly linked list
c) Write a C program that uses functions to perform deletion operation on a singly linked list
Description:
Linked lists are among the simplest and most common data structures. They can be used to
implement several other common abstract data types, including stacks, queues, associative arrays,
and symbolic expressions, The principal benefit of a linked list over a conventional array is that the
list elements can easily be inserted or removed without reallocation or reorganization of the entire
structure because the data items need not be stored contiguously in memory or on disk. Linked lists
allow insertion and removal of nodes at any point in the list, and can do so with a constant number
of operations if the link previous to the link being added or removed is maintained during list
traversal.
On the other hand, simple linked lists by themselves do not allow random access to the data,
or any form of efficient indexing. Thus, many basic operations — such as obtaining the last node of
the list (assuming that the last node is not maintained as separate node reference in the list structure),
or finding a node that contains a given datum, or locating the place where a new node should be
inserted — may require scanning most or all of the list elements.
Algorithm:
/* Singly_linkedlist */
declare struct linkedlist
integer data
struct linkedlist *next
typedef struct linkedlist node; Step 1:
Start
Step 2:head =NULL
Step3: repeat steps from 3 to 12 if ch!=9
Algorithm
createnode()
//input: nothing
//output: assign a node null and returns that node after allocating it
memorydynamically.
Step 1: Allocate the memory for new node
Step 2: Read value of item
Step 3:Assign values to NEW node data part
Step 4:Assign NEW node address part as null
Step5: return NEW node
Step9: prev=temp
Step10: temp=temp->next
Step11: if(temp!=NULL) then goto step12 else goto step15
Step12: NEW = createnode()
Step13: NEW->next = temp
Step14: prev->next = NEW
Step15: stop
Sample Input:
1.Add at beginning
2.Add at location
3. Add at end
4.Deletion
5.Display
6. exit
Enter your choice : 1
Enter the value : 33
1. Add at beginning
2. Add at location
3. Add at end
4. Deletion
5. Exit
Enter your choice : 1
Enter the value : 38
Add at beginning
1. Add at location
2. Add at end
3. Deletion
4. Display
5. Exit
Enter your choice : 1
Enter the value : 40
1. Add at beginning
2. Add at location
3. Add at end
4. Deletion
5. Display
6. Exit
Enter your choice : 5
The elements in single linked list: 33 38 40
Observed Output:
Viva Questions:
EX. NO: 9(A) ADDITION OF TWO LARGE INTEGERS USING LINKED LIST
Aim:
Write a C program for adding two large integers which are represented in linked list fashion.
Description:
Given two linked list, each node contains one digit number, we need to add these two linked
list. Result should be stored in third linked list. It should be noted that the head node contains the
most significant digit of the number. For example, two numbers 12345 and 56789 are represented in
form of linked list as follows:
Algorithm:
Sample Input:
Enter the first number a= 2->1->7
Enter the second number b= 3->4
Result= 2->5->1
Observed Output:
Aim:
Description:
Reversing the linked list starting from the very first node – the head node. What it basically
comes down to is changing pointers from one node to the next so that the entire linked list becomes
reversed. There is definitely a processm that we will want to follow in order to do that:
1. The head node’s next pointer should be set to NULL since the head will become the tail. This is
an exception for the head node, and can be done outside the while loop. But, before we do this we
will need a temp variable to point to the 2nd node (the node after the head node), because the only
way to reference the 2nd node is through the head node’s next pointer.
2. The 2nd node (the node after the head node) should have it’s own next pointer changed to point to
the head node. This will reverse the order of the nodes. But, remember that the 2nd node’s next
pointer will at first be pointing to the 3rd node. This means that before we change the 2nd node’s
next pointer, we have to save a reference to the 3rd node otherwise we will have no way of
referencing the 3rd node. So, we simply store a reference to the 3rd node in a variable before we
change the 2nd node’s next pointer.
3. The 3rd node then becomes the “first” node in the while loop and we repeat the process of
changing pointers described in step 2.
4. Continue step 3 until we come across a node that has a next pointer set to NULL. When we do
come across a NULL next pointer we just set the head node to point to the node that has the NULL
next pointer. This node was previously the tail node, but is now the head node because we are
reversing the linked list.
Algorithm:
struct node
{
int info;
struct node *link;
};
//create a node
typedef struct node *NODE;
NODE *first;
{
first=temp; return ;
}
Step 5: cur=first;
Step 6: add the temp at the end of the list, to reach the end do the following steps
while(cur->link!=NULL)
cur=cur->link;
Step 7: now add the temp at the end
cur->link=temp
Step 8: stop
{
r=q->link;
q->link=p;
p=q;
q=r;
}
q->link=p;
first->link=NULL;
first=q;
}
return;
}
Algorithm for display()
Step 1: if(first==NULL) then
printf("LIST EMPTY\n"); return;
Step 2: print ‗The contents of the list are‘
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
Step 3: stop.
Sample Input:
Enter no of elements: 4
Enter elements: 1 2 3 4
The elements are 1 2 3 4
After reversing 4 3 2 1
Observed Output:
Aim:
Description:
A polynomial may also be represented using a linked list. A structure may be defined such
that it contains two parts- one is the coefficient and second is the corresponding exponent. The
structure definition may be given as shown below:
Struct polynomial
{
int coefficient;
int exponent;
struct polynomial *next;
};
Thus the above polynomial may be represented using linked list as shown below:
Algorithm:
/* algorithm for storing a polynomial expression in memory using linked list*/ Declare
structure:
Struct node
{
float coeff;
int exp;
struct node * link;
};
typedef struct node * node;
Node first= null;
1: start
2: declare p g node type
3: declare ch, I, new integer type and assign i=1
4: declare c g float type
5: read n.
6: while i<=n
6.1: read c, e
6.2: increment I by 1
6.3: if first!=0 then
6.3.1: assign p=first
6.3.2: while(p->link)!=0
do
6.3.3: p=(p->link)
6.3.4: allocate memory to p->link using getnode()
6.3.5: assign p=(p->link)
6.3.6: (p->coeff)=c and (p->exp)=e
6.3.7: assign (p->link)=null
6.3.8:end if.
6.4 : else do
6.4.1 : (first)=getnode().
6.4.2 : (first -> coeff)=c.
6.4.3 : (first -> link)=null
6.4.4 : end else
7. end while
8. call display() function.
9. end.
1. Start
2. Declare ‗x‘ of node type
3. Allocate memory tox using ‗malloc‘ library function
The syntax follows
=(node) malloc (size of (struct node));
4. If x=null then
Print ―memory cannot be allocated‖.
4.1 call exit (0).
4.2 End if
5. Return the value of x.
6. End.
3.1.2 return.
3.1.3 end if
4. Assign temp= first.
5. While temp!= 0 do
5.1: temp =(temp ->link)
5.2: end while.
6. end.
Sample Input:
Observed Output:
EX. NO: 9(D) REPRESENT THE GIVEN SPARSE MATRIX USING ARRAYS
Aim:
Description:
A matrix that has relatively few non-zero entries. It may be represented in much less than n ×
m space. An n × m matrix with k non-zero entries is sparse if k << n × m. It may be faster to
represent the matrix compactly as a list of the non-zero indexes and associated entries, as a list of
lists of entries (one list for each row), coordinate format (the values and their row/column positions),
or by a point access method.
Algorithm:
/*Algorithm for main function*/
Step 1 print ‗Enter matrix size as mxn\t: :‘
Step 2 read m,n values set count=0, k=1,i=0.
Step 3. Repeat step 3 until i<m
Step 3.1. Repeat step 3.1 until j<n
Step 3.1.1 printf ‘nelementA ,i,j‘
Step 3.1.2 read a[i][j]
Step 4 assign i=0,j=0;
Step 5. Repeat step 5 until i<m
Step 5.1 Repeat step 5.1 until j<n
Step 5.1.1 check a[i][j] !=0 if true
Step 5.1.1.1 assign spm[k][0]=I ,spm[k][1]=j,spm[k++][2]=a[i][j].
Step 5.1.1.2 increment count
Step 6. assign spm[0][0]=m, spm[0][1]=n, spm[0][2]=count.
Step 7. Printf ‗nsparse matrix is : :\n‘
Step 8. Repeat step 8 until i<m
Step 8.1.Repeat step 8.1 until j<n
Step 8.1.1 printf ‘spm[i][j \n ]
Step 9 getch();
Sample Input:
Enter the no of rows: 3
Enter the no of columns: 3
Enter the elements in the array :
1
0
7
5
0
0
3
4
7
Elements of the matrix:
1 0 7
5 0 0
3 4 7
Elements of sparse matrix:
0 0 1
0 2 7
1 0 5
2 0 3
2 1 4
2 2 7
Observed Output:
EX. NO: 9(E) REPRESENT THE GIVEN SPARSE MATRIX USING LINKED LIST
Aim:
Write a C programme to representation the given sparse matrix using linked list.
Description:
A matrix that has relatively few non-zero entries. It may be represented in much less than n ×
m space. An n × m matrix with k non-zero entries is sparse if k << n × m. It may be faster to
represent the matrix compactly as a list of the non-zero indexes and associated entries, as a list of
lists of entries (one list for each row), coordinate format (the values and their row/column positions),
or by a point access method. It is implemented with linked list
Algorithm:
struct spars
{
int row,col,item;
struct spars*next; }ptr;
structhead_sp
{ introws,col,item;
struct spars * next; }*header;
1. Start
2. Declarei,j as integer type
3. Allocating memory to the header pointerusingmalloc function syntax
follows Header=(structhead_sp*)malloc(sizeof(structhead_sp));
4. Read header->rows, heade->cols, header->items;
5. If(header->item)=0 then
5.1. Exit(0);
5.2. End if
6. Allocate memory to (header_next) (struct spars*)maloc(sizeof(struct spars));
7. Read header->next->row,header->next->col,header->next->item
8. Initializing ptr=(header->next)
9. Create nodes for sparse matrix elements For(i=2 where i<=header:i++)
9.1. Allocate memory for(ptr next)
9.2. Initialize ptr=(ptr->next)
9.3. End for loop
10. Assign(ptr->next)->NULL
11. Displaying the matrix elements
11.1. Ptr=(headernext)
11.2. For(i=0;i<(headerrows;i++)
11.2.1.1. For(j=0;j<(headercols);j++
11.2.1.1.1.1. If ptr!=NULL then
11.2.1.1.1.1.1.1.1. Ifi=(ptrrows) and j=(ptrcol)then
11.2.1.1.1.1.1.1.2. Ptr=(ptrnext)
11.2.1.1.1.1.1.1.3. Otherwise print (―0\‖)
11.2.1.2otherwise print(―0\‖);
11.2.1.3end if
11.2.2 end for
11.3 end for
12.end
Sample Input:
Sparse Matrix using Linked List
0 0 1
0 1 8
1 1 7
2 0 7
Observed Output:
Viva questions:
1. Explain Traversing the Linked List
2. What does the following function do for a given Linked List?
3. When to use Linked List or Array List?
4. What is data structure?.
5. List out the areas in which data structures are applied extensively?
6. What are the major data structures used in the following areas : RDBMS, Network data
model and Hierarchical data model.
7. If you are using C language to implement the heterogeneous linked list, what pointer type
will you use?
8. Minimum number of queues needed to implement the priority queue?
9. What is the data structures used to perform recursion?
10. What are the notations used in Evaluation of Arithmetic Expressions using prefix and
postfix forms?
12. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and Postfix
notations.
13. Sorting is not possible by using which of the following methods? (Insertion, Selection,
Exchange, Deletion)
Description:
A binary tree is made of nodes, where each node contains a "left" reference, a "right"
reference, and a data element. The topmost node in the tree is called the root . Every node (excluding
a root) in a tree is connected by a directed edge from exactly one other node. This node is called a
parent. On the other hand, each node can be connected to arbitrary number of nodes, called children.
Nodes with no children are called leaves, or external nodes. Nodes which are not leaves are called
internal nodes. Nodes with the same parent are called siblings.
Algorithm:
Structure definition for node in a binary
tree typedefstructbst
{
int data;
struct bst *left,*right;
}node;
3.1. if(root->right==NULL)
3.2. Root->right=New;
3.3 else insert(root->right,New);
Step 4. else if (root->left==NULL)
4.1. root->left=New;
Step5. else insert(root->left,New);
INORDER_TRAVERSAL (NODE)
/* NODE refers to the Root node of the binary tree in its first call to the . Root node is the
starting point of the traversal */
If NODE NIL then
{
call INORDER_TRAVERSAL (LCHILD(NODE));
print (DATA (NODE)) ;
call INORDER_TRAVERSAL (RCHILD(NODE));
}
end INORDER_TRAVERSAL.
POSTORDER_TRAVERSAL (NODE)
/* NODE refers to the Root node of the binary tree in its first call to the . Root node is the
starting point of the traversal */
If NODE NIL then
{
call POSTORDER_TRAVERSAL (LCHILD(NODE));
call POSTORDER_TRAVERSAL (RCHILD(NODE));
print (DATA (NODE)) ;
}
end POSTORDER_TRAVERSAL.
PREORDER_TRAVERSAL (NODE)
/* NODE refers to the Root node of the binary tree in its first call to the . Root node is the
starting point of the traversal */
If NODE NIL then
{
print (DATA (NODE)) ; /* Process node (P) */
call PREORDER_TRAVERSAL (LCHILD(NODE));
call PREORDER_TRAVERSAL (RCHILD(NODE));
}
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE
92
DS LAB MANUAL
end PREORDER_TRAVERSAL.
Step 9: end
SampleOutput:
1. Insert
2. Inorder
3. Preorder
4. Postorder
5. Exit;
Enter your choice : 1
Enter the item 12
1. Insert
2. In order
3. Preorder
4. Postorder
5. Exit;
Enter your choice : 1
Enter the item 23
Where to insert left/right of root: l
1. Insert
2. Inorder
3. Preorder
4. Postorder
5. Exit;
Enter your choice : 1
Enter the item: 56
Where to insert left/right of root: r
1. Insert
2. Inorder
3. Preorder
4. Postorder
5. Exit;
Enter your choice : 2
Inorder:23 12 56
1. Insert
2. Inorder
3. Preorder
4. Postorder
5. Exit;
Enter your choice : 3
Preorder: 12 23 56
1. Insert
2. Inorder
3. Preorder
4. Postorder
5. Exit;
Enter your choice : 4
Postorder: 23 56 12
Observed Output:
Viva questions:
Aim:
a) Write a C program to Create a BST
b) Write a C programme to insert a note into a BST.
c) Write a C programme to delete a note from a BST.
Description:
Binary Search Tree, is a node-based binary tree data structure which has the following
properties:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.
ALGORITHM:
1: start
2: declare node *new,*root.
3: ans=N‘.
4: root=NULL.
5: do
5.1: read choice.
5.2: switch(choice)
Case:1
1.1root=NULL
1.2do
1.2.1: new=getnode();
1.2.2:read new=data.
1.2.3:if root=NULL then do
Root=new.
1.2.4:Else do
Insert(root,new).
1.2.5:read ans.
1.2.6:while ans=‘y‘ OR ‗Y‘
End do while
case 2:
1: if root=NULL do
Print ―tree not created ―.
2:else do
2.1:new=getnode().
2.2:read new=data.
2.3:insert(root,new).
case 3:read i.
Delete(root,i)
case 4: if root=NULL then do
Print ―tree not created‖.
ALGORITHM insert(T,ITEM):
/*T refers to the root node of the bst in its first call and item is the element to be inserted */
1.start
2.if T=NULL then do
2.1.T<-getnode()
2.2.T->LCHILD=NULL.
2.3.T->RCHILD=NULL
2.4.T->data=item
ALGORITHM delete(T,K).
//T refers to the root node of the bst and K is the item to be deleted
1.start
2.declare node *p,*s,*ps,*c,*pp
3.p<-T
4.while p!=NULL AND (p->data) !=K do
4.1 pp=p
4.2 if K<(p->data) then do
4.3 p=(p->LCHILD)
4.4 else do
p=p->RCHILD) 5.end
while
6.if !p then do
6.1 print ―no element with key K‖
6.2 return
7. if (p->LCHILD AND p->RCHILD )!=NULL then do
7.1 s=(p->LCHILD)
7.2ps=p
7.3 while s->RCHILD !=NULL do
7.3.1 ps=s
7.3.2 s=(s->RCHILD)
7.3.3 end while
7.4( p->data)=(s->data)
7.5 p=s
7.6 pp=ps
8. if (p->LCHILD!=NULL) then do
8.1 c = (p->LCHILD)
9.else do
9.1 c = ( p->RCHILD)
10. if (p = root) then do
10.1 root = c
11. else do
11.1 if (p == pp->LCHILD) then do
11.1.1 pp->LCHILD =c
11.2 else do
11.2.1 pp->RCHILD = c
12. free(p)
13. return
14. end
ALGORITHM inorder(T)
//inorder display of tree with root node T
1.start
2. if T=NULL then do
2.1 return
3.call inorder(T->LCHILD)
4.print ―T->data‖
5. call inorder(T->RCHILD)
6.end inorder
ALGORITHM preorder(T)
//preorder display of tree with root node T
1.start
2. if T=NULL then do
2.1 return
3.print ―T->data‖
4.call preorder(T->LCHILD)
5. call preorder(T->RCHILD)
6.end preorder
ALGORITHM postorder(T)
//postorder display of tree with root node T
1.start
2. if T=NULL then do
2.1 return
3.call postorder (T->LCHILD) 4.
call postorder (T->RCHILD)
5.print ―T->data‖
6.end postorder
Sample Input:
OPERATIONS—
1-Insert an element into tee
2-delete an element into tee
3-In order traversal
4-preoreder traversal
5-post order traversal
6-exit
Enter your choice:1
Enter data of node to be ionserted:40
Enter your choice:1
Enter data of node to be ionserted:20
Enter your choice:1
Enter data of node to be ionserted:10
Observed Output:
Viva questions:
EX. NO: 12(A) COMPUTE THE SHORTEST PATH OF A GRAPH USING DIJKSTRA’S
ALGORITHM
Aim:
Write a C programme to compute the shortest path of a graph using Dijkstra‘s algorithm
Descritpion
Dijkstra’s algorithm is a graph search algorithm that solves the single-source shortest path
problem for a graph with non-negative edge path costs, producing a shortest path tree. This
algorithm is often used in routing and as a subroutine in other graph algorithm.
Algorithm:
DIJKSTRA_SSSP(N, COST)
/*N is the number of vertices labeled { 1, 2, 3,…N} of the weighted digraph. COST[1:N,1:N] is the
cost matrix of the graph. If there is no edge then COST [i,j] = */
/* The computes the cost of the shortest path from vertex 1 the source, to every other
vertex of the weighted digraph */
end DIJKSTRA-SSSP .
Sample Input:
Enter the number f vertices: 4
Enter the adjacency matrix
0 1 1 1
1 0 1 0
1 1 0 1
1 0 1 0
Enter the starting node: 1
Distance of 0 =1
Path=0<-1
Distance of 2 =1
Path=2<-1
Distance of 3 =2
Path=3<-0<-1
Observed Output:
Aim:
Write a C programme to find the minimum spanning tree using Warshall‘s Algorithm
Description:
Warshall algorithm is a dynamic programming formulation, to solve the all-pairs
shortest path problem on directed graphs. It finds shortest path between all nodes in a graph. If
finds only the lengths not the path. The algorithm considers the intermediate vertices of a simple
path are any vertex present in that path other than the first and last vertex of that path.
Algorithm:
Algorithm: Warshall’s algorithm for finding minimum spanning tree.
WARSHALL(N, W)
/*N is the number of vertices labeled { 1, 2, 3,…N} of the weighted digraph. W[1:N,1:N] is the
cost matrix of the graph. If there is no edge then W [i,j] = . The final D matrix will store all the
shortest paths. */
for i = 1 to N do
for j = 1 to N do
if W[i][j] = 0 then D[i][j]=
; else D[i][j]= W[i][j];
end
end
for k = 1 to N do
for i = 1 to N do
for j = 1 to N do
Sample Input:
Enter the values of adjacency matrix
0 3 6 0 0 0 0
3 0 2 4 0 0 0
6 2 0 1 4 2 0
0 4 1 0 2 0 4
0 0 4 2 0 2 1
0 0 2 2 0 2 1
0 0 0 4 1 1 0
Minimum cost with respect to Node:0
0 3 5 6 8 7 8
Minimum cost with respect to Node:1
3 0 2 3 5 4 5
Minimum cost with respect to Node:2
5 2 0 1 3 2 3
Minimum cost with respect to Node:3
6 3 0 1 2 3 3
Minimum cost with respect to Node:4
8 5 3 2 0 2 1
Minimum cost with respect to Node:5
7 4 2 3 2 0 1
Viva Questions:
Aim:
Write a C program that implements Circular Queue and its operations using arrays.
Description:
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 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.
Circular linked list fallow the First In First Out principle
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”.
Items can inserted and deleted from a queue in O(1) time.
.
Algorithm:
In circular queue, the insertion of a new element is performed at the very first location of the
queue if the last location of the queue is full, in which the first element comes just after the last
element.
Insertion and Deletion:
Rear = (rear+1)%Maxsize
Alogarithm Steps:
Step 1: create and set the variables front,rear,MAXSIZE,cq[]
Step 2: Read the circular queue opeartion type.
Step 3: If operation type is Insertion below steps are executed.
1. Assign rear=rear%MAXSIZE.
2. if front equal to (rear+1)%MAXSIZE then display queue is overflow.
3. if front equal to -1 then assign front=rear=0.
4. Otherwise assign rear=(rear+1)%MAXSIZE and read queue data .
5. Assign cq[rear] as data.(i.e. cq[rear]=data).
Step 4: If operation type is Deletion below steps are executed.
1. Check front=-1 then display queue is underflow.
2. Set temp as cq[front] (i.e. temp=ca[front]).
3. Check front equal to rear if it is true then assign front=rear=-1(Move the front to begining)
4. Assign front=(front+1)%MAXSIZE.
Sample Input:
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR=0 FRONT=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR=1 FRONT=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR=2 FRONT=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR=3 FRONT=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR=4 FRONT=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR =4 FRONT=1
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR =4 FRONT=2
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR =4 FRONT=3
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
REAR =4 FRONT=4
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
Obserevd Output:
Viva questions:
Aim:
Write a C Program to perform various operations such as creation, insertion, deletion, search and
display on doubly link lists (DLL).
Descritpion:
Doubly Linked List is a variation of Linked list in which navigation is possible in both
ways, either forward and backward easily as compared to Single Linked List. Following are
the important terms to understand the concept of doubly linked list.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
Prev − Each link of a linked list contains a link to the previous link called Prev.
LinkedList − A Linked List contains the connection link to the first link called First and
to the last link called Last.
4. Read
switch(ch)
Do
Case1:append (head);
Case2:forward_display(head);
Case3:insert_after(head);
Case4:insert_before(head);
Case5: delnode(&head);
Case6:search(node);
Case7:destroy(head);
Case8:exit;
Default;
5. Endswitch
6. End while
7. Stop.
Algorithm createnode()
Input: null
Output: a node is created by using malloc function and the node is returned.
1. Start
2. Create a node ―new‖ using malloc
//new=(struct node*)malloc (sizeof(struct node));
3. Read the data into node ‗X‘.
4. Assign new(llink)=null;
New(rlink)=null;
5. Stop.
Algorithm append(node)
Input: the first created node
Output: the node created will be added to the existing dist and will be returned.
1. Start
2. Assign new=createnode();
3. If(*h=null)
{
*h=new;
Return;
}
4. Temp=*h;
5. Repeat
while(temp(rlink)!=null)
Temp=temp(rlink);
Temp=(rlink)=new;
New(llink)=temp;
6. End while
7. Stop.
Display p(data),
and P=p(rlink)
3. End while
4. Display the contents of the list.
5. Stop
Algorithm insert_after(node,*h)
Input: an node is inserted in the list in forward order
1. Start
2. Repeat while(p@= null) Do
Display p(data),
and P=p(rlink)
3. End while
4. Display the contents of the list
5. Stop.
Temp=temp(rlink) End
8. If(temp!=null) Do
New=create node();
New(rlink)=temp;
New(llink)=temp(llink);
New(llink)=rlink(new);
Temp->llink=new;
9. End if
10. End
11. Stop
Temp=temp(rlink)
End
If (temp!=null)
Do
Temp(rlink)(llink)=temp(llink);
Temp(llink)(rlink)=temp(rlink);
10. display the node and and the data
11. free the memory of the node
12. end while
13. stop
Algorithm search(node)
Input: a node is inserted and a pointer variable h is declared
Output: display the searched node with particular data
1. Start
2. Declare ‗K‘ of integer type
3. If (h=null)return
4. Read k
5. Temp=h
6. Repeat while (temp!=null and temp(data)!=k)do
7. Temp=temp->rlink
If(temp=null)
8. Display node does not
Node exist
9. Stop
Input: node
Output: deletes entire list and displays the list
1. Start
2. If(*h=null)return
3. Repeat while
(*h!=nul)do
P=(*h)rlink;
Free(*h);
4. *h=p;
5. Display linked list is destroyed
6. stop
Sample Input:
1.Add at beginning
2.Add at location
3. Add at end
4.Deletion
5.Display
6. exit
Enter your choice : 1
Enter the value : 33
6. Add at beginning
7. Add at location
8. Add at end
9. Deletion
10. Exit
Observed Output;
Viva questions: