#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:
//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:
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.
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.
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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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
---------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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
---------------------------------
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
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
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;
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
19
int key;
20
21
node *get_node();
22
root = NULL;
23
clrscr();
24
25
26
do {
27
printf("\n1.Create");
28
printf("\n2.Search");
29
printf("\n3.Recursive Traversals");
30
printf("\n4.Exit");
31
32
scanf("%d", &choice);
33
34
switch (choice) {
35
case 1:
36
do {
37
new_node = get_node();
38
39
scanf("%d", &new_node->data);
40
41
42
43
44
45
46
47
ans = getch();
48
49
break;
50
51
case 2:
52
53
scanf("%d", &key);
54
55
56
57
break;
58
59
case 3:
60
if (root == NULL)
61
62
else {
63
64
inorder(root);
65
66
preorder(root);
67
68
postorder(root);
69
70
break;
71
72
73 }
74 /*
75 Get new Node
76 */
77 node *get_node() {
78
node *temp;
79
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
89
if (root->lchild == NULL)
90
root->lchild = new_node;
91
else
92
93
insert(root->lchild, new_node);
}
94
95
96
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
112
return temp;
113
114
*parent = temp;
115
116
117
118
119
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 */
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
1 preorder(node)
2 {
3 if node = null
4
then
return
6 else
7
10 }
Inorder
LVR
Preorder
VLR
Postorder
LRV
#include<stdio.h>
functions#include<stdlib.h>
void dfs();
void bfs();
struct link
{
struct node *next;
struct link *adj;
};
struct node
{
int data,status;
struct node *next;
struct link *adj;
};
struct node *start,*p,*q;
void create()
{
int dat,flag=0;dat=1;
'1'start=NULL;
elements
break;
p=(struct node*)malloc(sizeof(struct node)); //reserving memory space for nodal element p>data=dat;
p->status=0;
p->next=NULL;
>adj=NULL;
if(flag==0)
procedure
{
start=p;
q=p;
flag++;
}
methodelse
{
q->next=p;
q=p;
}
}
loopp=start;
locationwhile(p!=NULL)
{
printf("Enter the links to %d (0 to end) : ",p->data);
flag=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
{
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)
{
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)
{
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;
}
}
}
int main()
{
int ch;
create();
while(1)
{
printf("1: DFS\n2: BSF\n0: Exit\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
dfs();
break;
case 2:
bfs();
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
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.
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;
};
{
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) );
can be atmost V^2, so O(LogV) are O(LogE) same. Therefore, overall time complexity is
O(ElogE) or O(ElogV)
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.
{
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.
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).
{
// 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;
12
19
21
11
14