You are on page 1of 84

//LINEAR SEARCH:

#include <stdio.h>
int main()
{
int array[100], search, c, n, count = 0;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d numbers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) {
printf("%d is present at location %d.\n", search, c+1);
count++;
}
}
if (count == 0)
printf("%d is not present in array.\n", search);
else
printf("%d is present %d times in array.\n", search, count);
return 0;
}

Output of code:

//BINARY SEARCH:
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);

break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
Output of program:

/* insertion sort ascending order */


#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}

for (c = 1 ; c <= n - 1; c++) {


d = c;
while ( d > 0 && array[d] < array[d-1]) {
t
= array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) {
printf("%d\n", array[c]);
}
return 0;
}
Output of program:

//SELECTION SORT
#include <stdio.h>
int main()
{
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");

scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}

Output of program:

//BUBBLE SORT
/* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)

{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap
= array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Output of program:

SINGLY LINKED LIST IMPLEMENTATION IN C:


C Program to Implement Singly Linked List using Dynamic Memory Allocation
This C Program Implements Singly Linked List using Dynamic Memory Allocation.

Here is source code of the C Program to Implement Singly Linked List using Dynamic Memory
Allocation. The C program is successfully compiled and run on a Linux system. The program
output is also shown below.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.

/*
* C Program to Implement Singly Linked List using Dynamic Memory Allocation
*/
#include <stdio.h>
#include <malloc.h>
#define ISEMPTY printf("\nEMPTY LIST:");
/*
* Node Declaration
*/
struct node
{
int value;
struct node *next;
};
snode* create_node(int);
void insert_node_first();
void insert_node_last();
void insert_node_pos();
void sorted_ascend();
void delete_pos();
void search();
void update_val();
void display();
void rev_display(snode *);
typedef struct node snode;
snode *newnode, *ptr, *prev, *temp;
snode *first = NULL, *last = NULL;
/*
* Main :contains menu
*/
int main()
{
int ch;
char ans = 'Y';

40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.

while (ans == 'Y'||ans == 'y')


{
printf("\n---------------------------------\n");
printf("\nOperations on singly linked list\n");
printf("\n---------------------------------\n");
printf("\n1.Insert node at first");
printf("\n2.Insert node at last");
printf("\n3.Insert node at position");
printf("\n4.Sorted Linked List in Ascending Order");
printf("\n5.Delete Node from any Position");
printf("\n6.Update Node Value");
printf("\n7.Search Element in the linked list");
printf("\n8.Display List from Beginning to end");
printf("\n9.Display List from end using Recursion");
printf("\n10.Exit\n");
printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("\nEnter your choice");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\n...Inserting node at first...\n");
insert_node_first();
break;
case 2:
printf("\n...Inserting node at last...\n");
insert_node_last();
break;
case 3:
printf("\n...Inserting node at position...\n");
insert_node_pos();
break;
case 4:
printf("\n...Sorted Linked List in Ascending Order...\n");
sorted_ascend();
break;
case 5:
printf("\n...Deleting Node from any Position...\n");
delete_pos();
break;
case 6:
printf("\n...Updating Node Value...\n");

83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.

update_val();
break;
case 7:
printf("\n...Searching Element in the List...\n");
search();
break;
case 8:
printf("\n...Displaying List From Beginning to End...\n");
display();
break;
case 9:
printf("\n...Displaying List From End using Recursion...\n");
rev_display(first);
break;
case 10:
printf("\n...Exiting...\n");
return 0;
break;
default:
printf("\n...Invalid Choice...\n");
break;
}
printf("\nYOU WANT TO CONTINUE (Y/N)");
scanf(" %c", &ans);
}
return 0;
}
/*
* Creating Node
*/
snode* create_node(int val)
{
newnode = (snode *)malloc(sizeof(snode));
if (newnode == NULL)
{
printf("\nMemory was not allocated");
return 0;
}
else
{
newnode->value = val;
newnode->next = NULL;

126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.

return newnode;
}
}
/*
* Inserting Node at First
*/
void insert_node_first()
{
int val;
printf("\nEnter the value for the node:");
scanf("%d", &val);
newnode = create_node(val);
if (first == last && first == NULL)
{
first = last = newnode;
first->next = NULL;
last->next = NULL;
}
else
{
temp = first;
first = newnode;
first->next = temp;
}
printf("\n----INSERTED----");
}
/*
* Inserting Node at Last
*/
void insert_node_last()
{
int val;
printf("\nEnter the value for the Node:");
scanf("%d", &val);
newnode = create_node(val);
if (first == last && last == NULL)
{
first = last = newnode;
first->next = NULL;

169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.

last->next = NULL;
}
else
{
last->next = newnode;
last = newnode;
last->next = NULL;
}
printf("\n----INSERTED----");
}
/*
* Inserting Node at position
*/
void insert_node_pos()
{
int pos, val, cnt = 0, i;
printf("\nEnter the value for the Node:");
scanf("%d", &val);
newnode = create_node(val);
printf("\nEnter the position ");
scanf("%d", &pos);
ptr = first;
while (ptr != NULL)
{
ptr = ptr->next;
cnt++;
}
if (pos == 1)
{
if (first == last && first == NULL)
{
first = last = newnode;
first->next = NULL;
last->next = NULL;
}
else
{
temp = first;
first = newnode;
first->next = temp;
}

212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.

printf("\nInserted");
}
else if (pos>1 && pos<=cnt)
{
ptr = first;
for (i = 1;i < pos;i++)
{
prev = ptr;
ptr = ptr->next;
}
prev->next = newnode;
newnode->next = ptr;
printf("\n----INSERTED----");
}
else
{
printf("Position is out of range");
}
}
/*
* Sorted Linked List
*/
void sorted_ascend()
{
snode *nxt;
int t;
if (first == NULL)
{
ISEMPTY;
printf(":No elements to sort\n");
}
else
{
for (ptr = first;ptr != NULL;ptr = ptr->next)
{
for (nxt = ptr->next;nxt != NULL;nxt = nxt->next)
{
if (ptr->value > nxt->value)
{
t = ptr->value;
ptr->value = nxt->value;

255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.

nxt->value = t;
}
}
}
printf("\n---Sorted List---");
for (ptr = first;ptr != NULL;ptr = ptr->next)
{
printf("%d\t", ptr->value);
}
}
}
/*
* Delete Node from specified position in a non-empty list
*/
void delete_pos()
{
int pos, cnt = 0, i;
if (first == NULL)
{
ISEMPTY;
printf(":No node to delete\n");
}
else
{
printf("\nEnter the position of value to be deleted:");
scanf(" %d", &pos);
ptr = first;
if (pos == 1)
{
first = ptr->next;
printf("\nElement deleted");
}
else
{
while (ptr != NULL)
{
ptr = ptr->next;
cnt = cnt + 1;
}
if (pos > 0 && pos <= cnt)
{

298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.

ptr = first;
for (i = 1;i < pos;i++)
{
prev = ptr;
ptr = ptr->next;
}
prev->next = ptr->next;
}
else
{
printf("Position is out of range");
}
free(ptr);
printf("\nElement deleted");
}
}
}
/*
* Updating Node value in a non-empty list
*/
void update_val()
{
int oldval, newval, flag = 0;
if (first == NULL)
{
ISEMPTY;
printf(":No nodes in the list to update\n");
}
else
{
printf("\nEnter the value to be updated:");
scanf("%d", &oldval);
printf("\nEnter the newvalue:");
scanf("%d", &newval);
for (ptr = first;ptr != NULL;ptr = ptr->next)
{
if (ptr->value == oldval)
{
ptr->value = newval;
flag = 1;
break;
}

341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.

}
if (flag == 1)
{
printf("\nUpdated Successfully");
}
else
{
printf("\nValue not found in List");
}
}
}
/*
* searching an element in a non-empty list
*/
void search()
{
int flag = 0, key, pos = 0;
if (first == NULL)
{
ISEMPTY;
printf(":No nodes in the list\n");
}
else
{
printf("\nEnter the value to search");
scanf("%d", &key);
for (ptr = first;ptr != NULL;ptr = ptr->next)
{
pos = pos + 1;
if (ptr->value == key)
{
flag = 1;
break;
}
}
if (flag == 1)
{
printf("\nElement %d found at %d position\n", key, pos);
}
else
{

384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.

printf("\nElement %d not found in list\n", key);


}
}
}
/*
* Displays non-empty List from Beginning to End
*/
void display()
{
if (first == NULL)
{
ISEMPTY;
printf(":No nodes in the list to display\n");
}
else
{
for (ptr = first;ptr != NULL;ptr = ptr->next)
{
printf("%d\t", ptr->value);
}
}
}
/*
* Display non-empty list in Reverse Order
*/
void rev_display(snode *ptr)
{
int val;
if (ptr == NULL)
{
ISEMPTY;
printf(":No nodes to display\n");
}
else
{
if (ptr != NULL)
{
val = ptr->value;
rev_display(ptr->next);
printf("%d\t", val);
}

427.
428.
429.

}
}

$gcc linkedlist.c
a.out
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
EMPTY LIST::No nodes in the list to display
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position

4.Sorted Linked List in Ascending Order


5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice5
...Deleting Node from any Position...
EMPTY LIST::No node to delete
YOU WANT TO CONTINUE (Y/N)
y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice6
...Updating Node Value...
EMPTY LIST::No nodes in the list to update

YOU WANT TO CONTINUE (Y/N)y


--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice
7
...Searching Element in the List...
EMPTY LIST::No nodes in the list
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value

7.Search Element in the linked list


8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice
3
...Inserting node at position...
Enter the value for the Node:1010
Enter the position 5
Position is out of range
YOU WANT TO CONTINUE (Y/N)
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice1
...Inserting node at first...
Enter the value for the node:100

----INSERTED---YOU WANT TO CONTINUE (Y/N)y


--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice1
...Inserting node at first...
Enter the value for the node:200
----INSERTED---YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value

7.Search Element in the linked list


8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
200 100
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice2
...Inserting node at last...
Enter the value for the Node:50
----INSERTED---YOU WANT TO CONTINUE (Y/N)y
---------------------------------

Operations on singly linked list


--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice2
...Inserting node at last...
Enter the value for the Node:150
----INSERTED---YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
200 100 50
150
YOU WANT TO CONTINUE (Y/N)
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice3
...Inserting node at position...
Enter the value for the Node:1111
Enter the position 4
----INSERTED---YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
---------------------------------

1.Insert node at first


2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
200 100 50
1111 150
YOU WANT TO CONTINUE (Y/N)
y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice3
...Inserting node at position...

Enter the value for the Node:1010


Enter the position 100
Position is out of range
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
200 100 50
1111 150
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position

6.Update Node Value


7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice5
...Deleting Node from any Position...
Enter the position of value to be deleted:1
Element deleted
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
100 50
1111 150
YOU WANT TO CONTINUE (Y/N)y
---------------------------------

Operations on singly linked list


--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice5
...Deleting Node from any Position...
Enter the position of value to be deleted:4
Element deleted
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
100 50
1111
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice5
...Deleting Node from any Position...
Enter the position of value to be deleted:2
Element deleted
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
---------------------------------

1.Insert node at first


2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
100 1111
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice6
...Updating Node Value...

Enter the value to be updated:100


Enter the newvalue:10101
Updated Successfully
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice8
...Displaying List From Beginning to End...
10101 1111
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position

6.Update Node Value


7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice6
...Updating Node Value...
Enter the value to be updated:100
Enter the newvalue:200
Value not found in List
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice7
...Searching Element in the List...
Enter the value to search 1111

Element 1111 found at 2 position


YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice7
...Searching Element in the List...
Enter the value to search200
Element 200 not found in list
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position

4.Sorted Linked List in Ascending Order


5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice4
...Sorted Linked List in Ascending Order...
---Sorted List---1111 10101
YOU WANT TO CONTINUE (Y/N)y
--------------------------------Operations on singly linked list
--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice9
...Displaying List From End using Recursion...
EMPTY LIST::No nodes to display
10101 1111
YOU WANT TO CONTINUE (Y/N)y

--------------------------------Operations on singly linked list


--------------------------------1.Insert node at first
2.Insert node at last
3.Insert node at position
4.Sorted Linked List in Ascending Order
5.Delete Node from any Position
6.Update Node Value
7.Search Element in the linked list
8.Display List from Beginning to end
9.Display List from end using Recursion
10.Exit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter your choice10
...Exiting...

C Program to Implement a Doubly Linked List & provide Insertion, Deletion & Display
Operations
This C Program implement a doubly linked list & provide insertion, deletion & display
operations. Doubly linked list is a linked data structure that consists of a set of sequentially
linked records called nodes. Each node contains two fields, called links, that are references to the
previous and to the next node in the sequence of nodes. The beginning and ending nodes
previous and next links, respectively, point to some kind of terminator, typically a sentinel node
or null, to facilitate traversal of the list. Here we need to preform insertion, deletion and display
all the modes of given doubly linked list.
Here is source code of the C Program to implement a doubly linked list & provide insertion,
deletion & display operations. The C program is successfully compiled and run on a Linux
system. The program output is also shown below.
/*
* C Program to Implement a Doubly Linked List & provide Insertion, Deletion & Display
Operations
*/

#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *prev;
int n;
struct node *next;
}*h,*temp,*temp1,*temp2,*temp4;
void insert1();
void insert2();
void insert3();
void traversebeg();
void traverseend(int);
void sort();
void search();
void update();
void delete();
int count = 0;
void main()
{
int ch;
h = NULL;
temp = temp1 = NULL;
printf("\n 1 - Insert at beginning");
printf("\n 2 - Insert at end");
printf("\n 3 - Insert at position i");
printf("\n 4 - Delete at i");
printf("\n 5 - Display from beginning");
printf("\n 6 - Display from end");
printf("\n 7 - Search for element");
printf("\n 8 - Sort the list");
printf("\n 9 - Update an element");
printf("\n 10 - Exit");
while (1)
{
printf("\n Enter choice : ");

scanf("%d", &ch);
switch (ch)
{
case 1:
insert1();
break;
case 2:
insert2();
break;
case 3:
insert3();
break;
case 4:
delete();
break;
case 5:
traversebeg();
break;
case 6:
temp2 = h;
if (temp2 == NULL)
printf("\n Error : List empty to display ");
else
{
printf("\n Reverse order of linked list is : ");
traverseend(temp2->n);
}
break;
case 7:
search();
break;
case 8:
sort();
break;
case 9:
update();
break;
case 10:
exit(0);
default:
printf("\n Wrong choice menu");
}
}

}
/* TO create an empty node */
void create()
{
int data;
temp =(struct node *)malloc(1*sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
printf("\n Enter value to node : ");
scanf("%d", &data);
temp->n = data;
count++;
}
/* TO insert at beginning */
void insert1()
{
if (h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp->next = h;
h->prev = temp;
h = temp;
}
}
/* To insert at end */
void insert2()
{
if (h == NULL)
{
create();
h = temp;
temp1 = h;
}

else
{
create();
temp1->next = temp;
temp->prev = temp1;
temp1 = temp;
}
}
/* To insert at any position */
void insert3()
{
int pos, i = 2;
printf("\n Enter position to be inserted : ");
scanf("%d", &pos);
temp2 = h;
if ((pos < 1) || (pos >= count + 1))
{
printf("\n Position out of range to insert");
return;
}
if ((h == NULL) && (pos != 1))
{
printf("\n Empty list cannot insert other than 1st position");
return;
}
if ((h == NULL) && (pos == 1))
{
create();
h = temp;
temp1 = h;
return;
}
else
{
while (i < pos)
{
temp2 = temp2->next;
i++;
}
create();

temp->prev = temp2;
temp->next = temp2->next;
temp2->next->prev = temp;
temp2->next = temp;
}
}
/* To delete an element */
void delete()
{
int i = 1, pos;
printf("\n Enter position to be deleted : ");
scanf("%d", &pos);
temp2 = h;
if ((pos < 1) || (pos >= count + 1))
{
printf("\n Error : Position out of range to delete");
return;
}
if (h == NULL)
{
printf("\n Error : Empty list no elements to delete");
return;
}
else
{
while (i < pos)
{
temp2 = temp2->next;
i++;
}
if (i == 1)
{
if (temp2->next == NULL)
{
printf("Node deleted from list");
free(temp2);
temp2 = h = NULL;
return;
}
}

if (temp2->next == NULL)
{
temp2->prev->next = NULL;
free(temp2);
printf("Node deleted from list");
return;
}
temp2->next->prev = temp2->prev;
if (i != 1)
temp2->prev->next = temp2->next; /* Might not need this statement if i == 1 check */
if (i == 1)
h = temp2->next;
printf("\n Node deleted");
free(temp2);
}
count--;
}
/* Traverse from beginning */
void traversebeg()
{
temp2 = h;
if (temp2 == NULL)
{
printf("List empty to display \n");
return;
}
printf("\n Linked list elements from begining : ");
while (temp2->next != NULL)
{
printf(" %d ", temp2->n);
temp2 = temp2->next;
}
printf(" %d ", temp2->n);
}
/* To traverse from end recursively */
void traverseend(int i)
{
if (temp2 != NULL)
{

i = temp2->n;
temp2 = temp2->next;
traverseend(i);
printf(" %d ", i);
}
}
/* To search for an element in the list */
void search()
{
int data, count = 0;
temp2 = h;
if (temp2 == NULL)
{
printf("\n Error : List empty to search for data");
return;
}
printf("\n Enter value to search : ");
scanf("%d", &data);
while (temp2 != NULL)
{
if (temp2->n == data)
{
printf("\n Data found in %d position",count + 1);
return;
}
else
temp2 = temp2->next;
count++;
}
printf("\n Error : %d not found in list", data);
}
/* To update a node value in the list */
void update()
{
int data, data1;
printf("\n Enter node data to be updated : ");
scanf("%d", &data);
printf("\n Enter new data : ");
scanf("%d", &data1);

temp2 = h;
if (temp2 == NULL)
{
printf("\n Error : List empty no node to update");
return;
}
while (temp2 != NULL)
{
if (temp2->n == data)
{
temp2->n = data1;
traversebeg();
return;
}
else
temp2 = temp2->next;
}
printf("\n Error : %d not found in list to update", data);
}
/* To sort the linked list */
void sort()
{
int i, j, x;
temp2 = h;
temp4 = h;
if (temp2 == NULL)
{
printf("\n List empty to sort");
return;
}
for (temp2 = h; temp2 != NULL; temp2 = temp2->next)
{
for (temp4 = temp2->next; temp4 != NULL; temp4 = temp4->next)
{
if (temp2->n > temp4->n)
{
x = temp2->n;

temp2->n = temp4->n;
temp4->n = x;
}
}
}
traversebeg();
}
$ cc pgm1.c
$ a.out
1 - Insert at beginning
2 - Insert at end
3 - Insert at position i
4 - Delete at i
5 - Display from beginning
6 - Display from end
7 - Search for element
8 - Sort the list
9 - Update an element
10 - Exit
Enter choice : 1
Enter value to node : 10
Enter choice : 2
Enter value to node : 50
Enter choice : 4
Enter position to be deleted : 1
Node deleted
Enter choice : 1
Enter value to node : 34
Enter choice : 3
Enter position to be inserted : 2

Enter value to node : 13


Enter choice : 4
Enter position to be deleted : 4
Error : Position out of range to delete
Enter choice : 1
Enter value to node : 15
Enter choice : 1
Enter value to node : 67
Enter choice : 3
Enter position to be inserted : 2
Enter value to node : 34
Enter choice : 4
Enter position to be deleted : 3
Node deleted
Enter choice : 7
Enter value to search : 15
Error : 15 not found in list
Enter choice : 8
Linked list elements from begining : 13 34 34 50 67
Enter choice : 9
Enter node data to be updated : 45
Enter new data : 89
Error : 45 not found in list to update
Enter choice : 9

Enter node data to be updated : 50


Enter new data : 90
Enter choice : 5
Linked list elements from begining : 13 34 34 90 67
Enter choice : 6
Reverse order of linked list is : 67 90 34 34 13
Enter choice : 7
Enter value to search : 90
Data found in 4 position
Enter choice : 8
Linked list elements from begining : 13 34 34 67 90
Enter choice : 7
Enter value to search : 90
Data found in 5 position
Enter choice : 9
Enter node data to be updated : 34
Enter new data : 56
Linked list elements from begining : 13 56 34 67 90
Enter choice : 10

C Program to Implement a Stack


This C Program implements stack. Stack is an area of memory that holds all local variables and
parameters used by any function, and remembers the order in which functions are called so that
function returns occur correctly. Each time a function is called, its local variables and parameters
are pushed onto" the stack. When the function returns, these locals and parameters are
popped." Because of this, the size of a programs stack fluctuates constantly as the program is
running, but it has some maximum size. This program has to perform push and pop operation of
stack.

Here is source code of the C program to implement a stack. The C program is successfully
compiled and run on a Linux system. The program output is also shown below.
/*
* C program to implement stack. Stack is a LIFO data structure.
* Stack operations: PUSH(insert operation), POP(Delete operation)
* and Display stack.
*/
#include <stdio.h>
#define MAXSIZE 5
struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
void push(void);
int pop(void);
void display(void);
void main ()
{
int choice;
int option = 1;
s.top = -1;
printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf ("
1 --> PUSH
\n");
printf ("
2 --> POP
\n");
printf ("
3 --> DISPLAY
\n");
printf ("
4 --> EXIT
\n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{

case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
/* Function to add an element to the stack */
void push ()
{
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
/* Function to delete an element from the stack */
int pop ()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);

}
else
{
num = s.stk[s.top];
printf ("poped element is = %dn", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
/* Function to display the status of the stack */
void display ()
{
int i;
if (s.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\n The status of the stack is \n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}
$ cc pgm100.c
$ a.out
STACK OPERATION
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
1
Enter the element to be pushed
34

Do you want to continue(Type 0 or 1)?


0
$ a.out
STACK OPERATION
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
1
Enter the element to be pushed
34
Do you want to continue(Type 0 or 1)?
1
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
2
poped element is = 34
Do you want to continue(Type 0 or 1)?
1
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
3
Stack is empty
Do you want to continue(Type 0 or 1)?
1
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT

-----------------------------------------Enter your choice


1
Enter the element to be pushed
50
Do you want to continue(Type 0 or 1)?
1
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
1
Enter the element to be pushed
60
Do you want to continue(Type 0 or 1)?
1
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
3
The status of the stack is
60
50
Do you want to continue(Type 0 or 1)?
1
-----------------------------------------1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
-----------------------------------------Enter your choice
4

C Program to Implement Binary Search Tree Traversal


C Program to implement Binary Search Tree Traversal

1 Preorder traversal sequence : F, B, A, D, C, E, G, I, H


2 (root, left, right)
3 Inorder traversal sequence : A, B, C, D, E, F, G, H, I
4 (left, root, right)
5 Postorder traversal sequence: A, C, E, D, B, H, I, G, F
6 (left, right, root)

Reference : http://en.wikipedia.org/wiki/Tree_traversal

Program :

1 # include <stdio.h>
2 # include <conio.h>
3 # include <stdlib.h>
4
5 typedef struct BST {
6

int data;

struct BST *lchild, *rchild;

8 } node;
9
10 void insert(node *, node *);
11 void inorder(node *);
12 void preorder(node *);
13 void postorder(node *);
14 node *search(node *, int, node **);
15
16 void main() {
17

int choice;

18

char ans = 'N';

19

int key;

20

node *new_node, *root, *tmp, *parent;

21

node *get_node();

22

root = NULL;

23

clrscr();

24
25

printf("\nProgram For Binary Search Tree ");

26

do {

27

printf("\n1.Create");

28

printf("\n2.Search");

29

printf("\n3.Recursive Traversals");

30

printf("\n4.Exit");

31

printf("\nEnter your choice :");

32

scanf("%d", &choice);

33
34

switch (choice) {

35

case 1:

36

do {

37

new_node = get_node();

38

printf("\nEnter The Element ");

39

scanf("%d", &new_node->data);

40
41
42
43
44

if (root == NULL) /* Tree is not Created */


root = new_node;
else
insert(root, new_node);

45
46

printf("\nWant To enter More Elements?(y/n)");

47

ans = getch();

48

} while (ans == 'y');

49

break;

50
51

case 2:

52

printf("\nEnter Element to be searched :");

53

scanf("%d", &key);

54
55

tmp = search(root, key, &parent);

56

printf("\nParent of node %d is %d", tmp->data, parent->data);

57

break;

58
59

case 3:

60

if (root == NULL)

61

printf("Tree Is Not Created");

62

else {

63

printf("\nThe Inorder display : ");

64

inorder(root);

65

printf("\nThe Preorder display : ");

66

preorder(root);

67

printf("\nThe Postorder display : ");

68

postorder(root);

69

70

break;

71

72

} while (choice != 4);

73 }
74 /*
75 Get new Node
76 */
77 node *get_node() {
78

node *temp;

79

temp = (node *) malloc(sizeof(node));

80

temp->lchild = NULL;

81

temp->rchild = NULL;

82

return temp;

83 }
84 /*
85 This function is for creating a binary search tree
86 */
87 void insert(node *root, node *new_node) {
88

if (new_node->data < root->data) {

89

if (root->lchild == NULL)

90

root->lchild = new_node;

91

else

92
93

insert(root->lchild, new_node);
}

94
95
96

if (new_node->data > root->data) {


if (root->rchild == NULL)

97
98

root->rchild = new_node;
else

99

insert(root->rchild, new_node);

100 }
101 }
102 /*
103 This function is for searching the node from
104 binary Search Tree
105 */
106 node *search(node *root, int key, node **parent) {
107 node *temp;
108 temp = root;
109 while (temp != NULL) {
110

if (temp->data == key) {

111

printf("\nThe %d Element is Present", temp->data);

112

return temp;

113

114

*parent = temp;

115
116
117
118
119

if (temp->data > key)


temp = temp->lchild;
else
temp = temp->rchild;

120 }
121 return NULL;

122 }
123 /*
124 This function displays the tree in inorder fashion
125 */
126 void inorder(node *temp) {
127 if (temp != NULL) {
128

inorder(temp->lchild);

129

printf("%d", temp->data);

130

inorder(temp->rchild);

131 }
132 }
133 /*
134 This function displays the tree in preorder fashion
135 */
136 void preorder(node *temp) {
137 if (temp != NULL) {
138

printf("%d", temp->data);

139

preorder(temp->lchild);

140

preorder(temp->rchild);

141 }
142 }
143
144 /*
145 This function displays the tree in postorder fashion
146 */

147 void postorder(node *temp) {


148 if (temp != NULL) {
149

postorder(temp->lchild);

150

postorder(temp->rchild);

151

printf("%d", temp->data);

152 }
153 }
Explanation :

get_node() function will allocate memory dynamically and allocate one node.
if below condition is satisfied then we can say that we are going to create first node of the
tree. (i.e Tree is empty and this created node is very first node)

1 if(root == NULL)

If condition does not satisfied then we can say that we have already node in a tree. (i.e
this node which we have created is not a first node)

Display Tree
To display tree we have 3 traversal Techniques
1.

In-Order Traversal

2.

Pre-Order Traversal

3.

Post-Order Traversal

Algorithm for Preorder Traversal of Binary Search Tree :

1 preorder(node)
2 {
3 if node = null
4

then

return

6 else
7

print Node Data

Go to Left Child of node

Go to Right Child of node

10 }

Similarly Post order and inorder traversal works.


Summary of Traversal of BST :
Traversal Type
Short Cut

Inorder
LVR

Preorder
VLR

Postorder
LRV

//C program to implement the Graph Traversal


//(a) Breadth first traversal
//(b) Depth first traversal

#include<stdio.h>
functions#include<stdlib.h>

//For standard input/output


//For standard library functions

void dfs();

// For Deapth First Search(DFS) Traversal

void bfs();

// For Breadth First Search(BFS) Traversal

struct link

// Structure for adjacency list

{
struct node *next;
struct link *adj;
};
struct node

// Structure for elements in the graph

{
int data,status;
struct node *next;
struct link *adj;
};
struct node *start,*p,*q;

//Declaring pointer variable for structure node

struct link *l,*k;

//Declaring pointer variable for structure node

void create()

// Function to Create the graph

{
int dat,flag=0;dat=1;
'1'start=NULL;

//Initializing 'flag' & 'dat' with a value of '0' &


//'start' pointing to NULL, as no value is being input till

nowprintf("Enter the nodes in the graph(0 to end): ");


while(dat)
{
scanf("%d",&dat);
if(dat==0)

//Getting the data from user


//If data entered is '0' then assume its the end of inputting

elements
break;
p=(struct node*)malloc(sizeof(struct node)); //reserving memory space for nodal element p>data=dat;

//storing the input data into node's data element

p->status=0;
p->next=NULL;

//next element is set to NULL p-

>adj=NULL;
if(flag==0)

//previous element is set to NULL


//If flag's value is zero then follow below

procedure
{
start=p;
q=p;
flag++;
}

//If flag's value is not zero then follow below

methodelse
{
q->next=p;
q=p;
}
}
loopp=start;

//Finishing the data entry


//Assigning the pointer 'p' the starting

locationwhile(p!=NULL)
{
printf("Enter the links to %d (0 to end) : ",p->data);
flag=0;

//Setting the initial value of 'flag' be '0'

while(1)
{
scanf("%d",&dat);
if(dat==0)
break;
k=(struct link*)malloc(sizeof(struct link));
"link" element k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{

//Allocating memory space for

l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==dat)
k->next=q;
q=q->next;
}
}
p=p->next;
}
}
void bfs()
{
int q[20],i=1,j=0;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
q[0]=p->data;
p->status=1;
while(1)
{
if(q[j]==0)
break;
p=start;
while(p!=NULL)
{

//Function for Breadth First Traversal of Graph

if(p->data==q[j])
break;
p=p->next;
}
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
q[i]=q->data;
q->status=1;
q[i+1]=0;
i++;
}
k=k->adj;
}
j++;
}
j=0;
printf("Breadth First Search Results\n");
while(q[j]!=0)

//For printing the BFS result array

{
printf("%d ",q[j]);
j++;
}
getche();
}//Function for Depth First Search(BFS) Traversal.
void dfs()
{
int stack[20],top=1;
printf("Deapth First Search Results");
p=start;

while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
stack[0]=0;
stack[top]=p->data;
p->status=1;
while(1)
{
if(stack[top]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==stack[top])
break;
p=p->next;
}
printf("%d ",stack[top]);
top--;
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
top++;
stack[top]=q->data;
q->status=1;
}
k=k->adj;
}

//Printing the DFS result

}
}
int main()
{
int ch;
create();

//Invoking the create function

while(1)
{
printf("1: DFS\n2: BSF\n0: Exit\nEnter your choice: ");
scanf("%d",&ch);

//User enters his choice

switch(ch)
{
case 1:
dfs();

//For Depth First Traversal

break;
case 2:
bfs();

//For Breadth First Traversal

break;
case 0:
exit(0);

//If Zero then exit the program (Omit this line if you don't want that)

break;
default:
printf("Incorrect choice!");
}
}
return 0;
}

//End of program

Greedy Algorithms | Set 2 (Kruskals Minimum Spanning Tree Algorithm)


What is Minimum Spanning Tree?
Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree
and connects all the vertices together. A single graph can have many different spanning

trees. A minimum spanning tree (MST)or minimum weight spanning tree for a weighted,
connected and undirected graph is a spanning tree with weight less than or equal to the weight of
every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge
of the spanning tree.
How many edges does a minimum spanning tree has?
A minimum spanning tree has (V 1) edges where V is the number of vertices in the given
graph.
What are the applications of Minimum Spanning Tree?
See this for applications of MST.
Below are the steps for finding MST using Kruskals algorithm
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.
The step#2 uses Union-Find algorithm to detect cycle. So we recommend to read following post
as a prerequisite.
Union-Find Algorithm | Set 1 (Detect Cycle in a Graph)
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that
does not cause a cycle in the MST constructed so far. Let us understand it with an example:
Consider the below input graph.

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be
having (9 1) = 8 edges.
After sorting:
Weight Src
1

Dest

10

11

14

Now pick all edges one by one from sorted list of edges
1. Pick edge 7-6: No cycle is formed, include it.
2. Pick edge 8-2: No cycle is formed, include it.

3. Pick edge 6-5: No cycle is formed, include it.

4. Pick edge 0-1: No cycle is formed, include it.

5. Pick edge 2-5: No cycle is formed, include it.

6. Pick edge 8-6: Since including this edge results in cycle, discard it.
7. Pick edge 2-3: No cycle is formed, include it.

8. Pick edge 7-8: Since including this edge results in cycle, discard it.
9. Pick edge 0-7: No cycle is formed, include it.

10. Pick edge 1-2: Since including this edge results in cycle, discard it.
11. Pick edge 3-4: No cycle is formed, include it.

Since the number of edges included equals (V 1), the algorithm stops here.
// Kruskal's algortihm to find Minimum Spanning Tree of a given connected,
// undirected and weighted graph
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// a structure to represent a weighted edge in graph
struct Edge
{
int src, dest, weight;
};

// a structure to represent a connected, undirected and weighted graph


struct Graph
{
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges. Since the graph is
// undirected, the edge from src to dest is also edge from dest
// to src. Both are counted as 1 edge here.
struct Edge* edge;
};
// Creates a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );
graph->V = V;
graph->E = E;
graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
return graph;
}
// A structure to represent a subset for union-find
struct subset
{
int parent;
int rank;
};
// A utility function to find set of an element i
// (uses path compression technique)
int find(struct subset subsets[], int i)
{
// find root and make root as parent of i (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(struct subset subsets[], int x, int y)

{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high rank tree
// (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and increment
// its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// Compare two edges according to their weights.
// Used in qsort() for sorting an array of edges
int myComp(const void* a, const void* b)
{
struct Edge* a1 = (struct Edge*)a;
struct Edge* b1 = (struct Edge*)b;
return a1->weight > b1->weight;
}
// The main function to construct MST using Kruskal's algorithm
void KruskalMST(struct Graph* graph)
{
int V = graph->V;
struct Edge result[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges
// Step 1: Sort all the edges in non-decreasing order of their weight
// If we are not allowed to change the given graph, we can create a copy of
// array of edges
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
// Allocate memory for creating V ssubsets
struct subset *subsets =
(struct subset*) malloc( V * sizeof(struct subset) );

// Create V subsets with single elements


for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
// Number of edges to be taken is equal to V-1
while (e < V - 1)
{
// Step 2: Pick the smallest edge. And increment the index
// for next iteration
struct Edge next_edge = graph->edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
// If including this edge does't cause cycle, include it
// in result and increment the index of result for next edge
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
// print the contents of result[] to display the built MST
printf("Following are the edges in the constructed MST\n");
for (i = 0; i < e; ++i)
printf("%d -- %d == %d\n", result[i].src, result[i].dest,
result[i].weight);
return;
}
// Driver program to test above functions
int main()
{
/* Let us create following weighted graph
10
0--------1
| \ |
6| 5\ |15
|
\|
2--------3
4
*/

int V = 4; // Number of vertices in graph


int E = 5; // Number of edges in graph
struct Graph* graph = createGraph(V, E);
// add edge 0-1
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 10;
// add edge 0-2
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 6;
// add edge 0-3
graph->edge[2].src = 0;
graph->edge[2].dest = 3;
graph->edge[2].weight = 5;
// add edge 1-3
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;
// add edge 2-3
graph->edge[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight = 4;
KruskalMST(graph);
return 0;
}
Run on IDE
Following are the edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Time Complexity: O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time. After sorting,
we iterate through all edges and apply find-union algorithm. The find and union operations can
take atmost O(LogV) time. So overall complexity is O(ELogE + ELogV) time. The value of E

can be atmost V^2, so O(LogV) are O(LogE) same. Therefore, overall time complexity is
O(ElogE) or O(ElogV)

Greedy Algorithms | Set 5 (Prims Minimum Spanning Tree (MST))


We have discussed Kruskals algorithm for Minimum Spanning Tree. Like Kruskals algorithm,
Prims algorithm is also a Greedy algorithm. It starts with an empty spanning tree. The idea is to
maintain two sets of vertices. The first set contains the vertices already included in the MST, the
other set contains the vertices not yet included. At every step, it considers all the edges that
connect the two sets, and picks the minimum weight edge from these edges. After picking the
edge, it moves the other endpoint of the edge to the set containing MST.
A group of edges that connects two set of vertices in a graph is called cut in graph theory. So, at
every step of Prims algorithm, we find a cut (of two sets, one contains the vertices already
included in MST and other contains rest of the verices), pick the minimum weight edge from the
cut and include this vertex to MST Set (the set that contains already included vertices).
How does Prims Algorithm Work? The idea behind Prims algorithm is simple, a spanning tree
means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices
must be connected to make a Spanning Tree. And they must be connected with the minimum
weight edge to make it a Minimum Spanning Tree.
Algorithm
1) Create a set mstSet that keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE.
Assign key value as 0 for the first vertex so that it is picked first.
3) While mstSet doesnt include all vertices
.a) Pick a vertex u which is not there in mstSet and has minimum key value.
.b) Include u to mstSet.
.c) Update key value of all adjacent vertices of u. To update the key values, iterate through all
adjacent vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous key
value of v, update the key value as weight of u-v
The idea of using key values is to pick the minimum weight edge from cut. The key values are
used only for vertices which are not yet included in MST, the key value for these vertices
indicate the minimum weight edges connecting them to the set of vertices included in MST.
Let us understand with the following example:

The set mstSet is initially empty and keys assigned to vertices are {0, INF, INF, INF, INF, INF,
INF, INF} where INF indicates infinite. Now pick the vertex with minimum key value. The
vertex 0 is picked, include it in mstSet. SomstSet becomes {0}. After including to mstSet, update
key values of adjacent vertices. Adjacent vertices of 0 are 1 and 7. The key values of 1 and 7 are

updated as 4 and 8. Following subgraph shows vertices and their key values, only the vertices
with finite key values are shown. The vertices included in MST are shown in green color.

Pick the vertex with minimum key value and not already included in MST (not in mstSET). The
vertex 1 is picked and added to mstSet. So mstSet now becomes {0, 1}. Update the key values of
adjacent vertices of 1. The key value of vertex 2 becomes 8.

Pick the vertex with minimum key value and not already included in MST (not in mstSET). We
can either pick vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0, 1, 7}.
Update the key values of adjacent vertices of 7. The key value of vertex 6 and 8 becomes finite
(7 and 1 respectively).

Pick the vertex with minimum key value and not already included in MST (not in mstSET).
Vertex 6 is picked. So mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent
vertices of 6. The key value of vertex 5 and 8 are updated.

We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get the
following graph.

How to implement the above algorithm?


We use a boolean array mstSet[] to represent the set of vertices included in MST. If a value
mstSet[v] is true, then vertex v is included in MST, otherwise not. Array key[] is used to store
key values of all vertices. Another array parent[] to store indexes of parent nodes in MST. The
parent array is the output array which is used to show the constructed MST.
// A C / C++ program for Prim's Minimum Spanning Tree (MST) algorithm.
// The program is for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
// Number of vertices in the graph
#define V 5
// A utility function to find the vertex with minimum key value, from
// the set of vertices not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
// A utility function to print the constructed MST stored in parent[]
int printMST(int parent[], int n, int graph[V][V])
{
printf("Edge Weight\n");
for (int i = 1; i < V; i++)
printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]);
}
// Function to construct and print MST for a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])

{
int parent[V]; // Array to store constructed MST
int key[V]; // Key values used to pick minimum weight edge in cut
bool mstSet[V]; // To represent set of vertices not yet included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V-1; count++)
{
// Pick thd minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of the adjacent vertices of
// the picked vertex. Consider only those vertices which are not yet
// included in MST
for (int v = 0; v < V; v++)
// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
// print the constructed MST
printMST(parent, V, graph);
}
// driver program to test above function
int main()
{
/* Let us create the following graph
2 3
(0)--(1)--(2)

| /\ |
6| 8/ \5 |7
|/ \|
(3)-------(4)
9
*/
int graph[V][V] = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
// Print the solution
primMST(graph);
return 0;
}
Run on IDE
Output:
Edge Weight
0-1

1-2

0-3

1-4

Time Complexity of the above program is O(V^2). If the input graph is represented using
adjacency list, then the time complexity of Prims algorithm can be reduced to O(E log V) with
the help of binary heap. We will soon be discussing O(E Log V) algorithm as a separate post.

Greedy Algorithms | Set 7 (Dijkstras shortest path algorithm)


Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the
given graph.
Dijkstras algorithm is very similar to Prims algorithm for minimum spanning tree. Like Prims
MST, we generate aSPT (shortest path tree) with given source as root. We maintain two sets, one
set contains vertices included in shortest path tree, other set includes vertices not yet included in
shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of
not yet included) and has minimum distance from source.
Below are the detailed steps used in Dijkstras algorithm to find the shortest path from a single
source vertex to all other vertices in the given graph.
Algorithm

1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path
tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is
empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesnt include all vertices
.a) Pick a vertex u which is not there in sptSetand has minimum distance value.
.b) Include u to sptSet.
.c) Update distance value of all adjacent vertices of u. To update the distance values, iterate
through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from
source) and weight of edge u-v, is less than the distance value of v, then update the distance value
of v.
Let us understand with the following example:

The set sptSetis initially empty and distances assigned to vertices are {0, INF, INF, INF, INF,
INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum distance value.
The vertex 0 is picked, include it insptSet. So sptSet becomes {0}. After including 0 to sptSet,
update distance values of its adjacent vertices. Adjacent vertices of 0 are 1 and 7. The distance
values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their distance
values, only the vertices with finite distance values are shown. The vertices included in SPT are
shown in green color.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}. Update the distance
values of adjacent vertices of 1. The distance value of vertex 2 becomes 12.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
Vertex 7 is picked. So sptSet now becomes {0, 1, 7}. Update the distance values of adjacent
vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9 respectively).

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. Update the distance values of adjacent
vertices of 6. The distance value of vertex 5 and 8 are updated.

We repeat the above steps until sptSet doesnt include all vertices of given graph. Finally, we get
the following Shortest Path Tree (SPT).

How to implement the above algorithm?


We use a boolean array sptSet[] to represent the set of vertices included in SPT. If a value
sptSet[v] is true, then vertex v is included in SPT, otherwise not. Array dist[] is used to store
shortest distance values of all vertices.
// A C / C++ program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])

{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance array
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
// Funtion that implements Dijkstra's single source shortest path algorithm
// for a graph represented using adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the shortest
// distance from src to i
bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < V-1; count++)
{
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in first iteration.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;

// Update dist value of the adjacent vertices of the picked vertex.


for (int v = 0; v < V; v++)
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u]+graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// print the constructed distance array
printSolution(dist, V);
}
// driver program to test above function
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
dijkstra(graph, 0);
return 0;
}
Run on IDE
Output:
Vertex Distance from Source
0

12

19

21

11

14

You might also like