Computer Practical
Computer Practical
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
static void reverse(struct Node** head_ref){
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
void push(struct Node** head_ref, int new_data){
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* head){
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
int main(){
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
printf("Given linked list\n");
printList(head);
reverse(&head);
printf("\nReversed linked list \n");
printList(head);
getchar();
}
Program 4
C program to merge two sorted linked lists.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void MoveNode(struct Node** destRef,
struct Node** sourceRef);
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node dummy;
struct Node* tail = &dummy;
dummy.next = NULL;
while (1) {
if (a == NULL) {
tail->next = b;
break;
}
else if (b == NULL) {
tail->next = a;
break;
}
if (a->data <= b->data)
MoveNode(&(tail->next), &a);
else
MoveNode(&(tail->next), &b);
tail = tail->next;
}
return (dummy.next);
}
void MoveNode(struct Node** destRef,
struct Node** sourceRef){
struct Node* newNode = *sourceRef;
assert(newNode != NULL);
*sourceRef = newNode->next;
newNode->next = *destRef;
*destRef = newNode;
}
void push(struct Node** head_ref, int new_data){
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* node){
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main(){
struct Node* res = NULL;
struct Node* a = NULL;
struct Node* b = NULL;
push(&a, 15);
push(&a, 10);
push(&a, 5);
push(&b, 20);
push(&b, 3);
push(&b, 2);
res = SortedMerge(a, b);
printf("Merged Linked List is: \n");
printList(res);
return 0;
}
Program 5
C program for linked list merged sort.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* SortedMerge(struct Node* a, struct Node* b);
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef);
void MergeSort(struct Node** headRef)
{
struct Node* head = *headRef;
struct Node* a;
struct Node* b;
if ((head == NULL) || (head->next == NULL)) {
return;
}
FrontBackSplit(head, &a, &b);
MergeSort(&a);
MergeSort(&b);
*headRef = SortedMerge(a, b);
}
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node* result = NULL;
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
if (a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return (result);
}
list->head = new_node;
list->size++;
}
void* remove_from_list(List* list) {
if (list->size == 0) {
return NULL;
}
Node* node_to_remove = list->head;
void* data = node_to_remove->data;
list->head = node_to_remove->next;
free(node_to_remove);
list->size--;
return data;
}
void free_list(List* list) {
Node* current_node = list->head;
while (current_node != NULL) {
Node* next_node = current_node->next;
free(current_node);
current_node = next_node;
}
free(list);
}
int main() {
List* int_list = create_list();
int x = 42;
add_to_list(int_list, (void*)&x);
int y = 13;
add_to_list(int_list, (void*)&y);
int z = 99;
add_to_list(int_list, (void*)&z);
int* int_ptr = NULL;
while ((int_ptr = (int*)remove_from_list(int_list)) != NULL) {
printf("%d\n", *int_ptr);
}
free_list(int_list);
return 0;
}
Program 11
C Program to convert infix to postfix expression
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_EXPR_SIZE 100
int precedence(char operator){
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
int isOperator(char ch){
return (ch == '+' || ch == '-' || ch == '*' || ch == '/'
|| ch == '^');
}
char* infixToPostfix(char* infix){
int i, j;
int len = strlen(infix);
char* postfix = (char*)malloc(sizeof(char) * (len + 2));
char stack[MAX_EXPR_SIZE];
int top = -1;
for (i = 0, j = 0; i < len; i++) {
if (infix[i] == ' ' || infix[i] == '\t')
continue;
if (isalnum(infix[i])) {
postfix[j++] = infix[i];
}
else if (infix[i] == '(') {
stack[++top] = infix[i];
}
else if (infix[i] == ')') {
while (top > -1 && stack[top] != '(')
postfix[j++] = stack[top--];
if (top > -1 && stack[top] != '(')
return "Invalid Expression";
else
top--;
}
else if (isOperator(infix[i])) {
while (top > -1
&& precedence(stack[top])
>= precedence(infix[i]))
postfix[j++] = stack[top--];
stack[++top] = infix[i];
}
}
while (top > -1) {
if (stack[top] == '(') {
return "Invalid Expression";
}
postfix[j++] = stack[top--];
}
postfix[j] = '\0';
return postfix;
}
int main(){
char infix[MAX_EXPR_SIZE] = "a+b*(c^d-e)^(f+g*h)-i";
char* postfix = infixToPostfix(infix);
printf("%s\n", postfix);
free(postfix);
return 0;
}
Program 12
C Program to Check for balance Bracket expression using Stack.
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct sNode {
char data;
struct sNode* next;
};void push(struct sNode** top_ref, int new_data);
int pop(struct sNode** top_ref);
bool isMatchingPair(char character1, char character2){
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
bool areBracketsBalanced(char exp[])
{
int i = 0;
struct sNode* stack = NULL;
while (exp[i]) {
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
if (exp[i] == '}' || exp[i] == ')'
|| exp[i] == ']') {
if (stack == NULL)
return 0;
else if (!isMatchingPair(pop(&stack), exp[i]))
return 0;
}
i++;
}
if (stack == NULL)
return 1; // balanced
else
return 0; // not balanced
}
int main(){
char exp[100] = "{()}[]";
if (areBracketsBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
void push(struct sNode** top_ref, int new_data)
{
struct sNode* new_node
= (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct sNode** top_ref){
char res;
struct sNode* top;
if (*top_ref == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
Program 13
C program to evaluate value of a postfix expression.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Stack {
int top;
unsigned capacity;
int* array;
};
struct Stack* createStack(unsigned capacity){
struct Stack* stack
= (struct Stack*)malloc(sizeof(struct Stack));
if (!stack)
return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array
= (int*)malloc(stack->capacity * sizeof(int));
if (!stack->array)
return NULL;
return stack;
}
int isEmpty(struct Stack* stack){
return stack->top == -1;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--];
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}
int evaluatePostfix(char* exp)
{
struct Stack* stack = createStack(strlen(exp));
int i;
if (!stack)
return -1;
for (i = 0; exp[i]; ++i) {
if (isdigit(exp[i]))
push(stack, exp[i] - '0');
else {
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i]) {
case '+':
push(stack, val2 + val1);
break;
case '-':
push(stack, val2 - val1);
break;
case '*':
push(stack, val2 * val1);
break;
case '/':
push(stack, val2 / val1);
break;
}
}
}
return pop(stack);
}
int main(){
char exp[] = "231*+9-";
printf("postfix evaluation: %d", evaluatePostfix(exp));
return 0;
}
Program 14
C program to reverse a stack using recursion.
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct sNode {
char data;
struct sNode* next;
};
void push(struct sNode** top_ref, int new_data);
int pop(struct sNode** top_ref);
bool isEmpty(struct sNode* top);
void print(struct sNode* top);
void insertAtBottom(struct sNode** top_ref, int item){
if (isEmpty(*top_ref))
push(top_ref, item);
else {
int temp = pop(top_ref);
insertAtBottom(top_ref, item);
push(top_ref, temp);
}
}
void reverse(struct sNode** top_ref){
if (!isEmpty(*top_ref)) {
int temp = pop(top_ref);
reverse(top_ref);
insertAtBottom(top_ref, temp);
}
}
int main(){
struct sNode* s = NULL;
push(&s, 4);
push(&s, 3);
push(&s, 2);
push(&s, 1);
printf("\n Original Stack ");
print(s);
reverse(&s);
printf("\n Reversed Stack ");
print(s);
return 0;
}
bool isEmpty(struct sNode* top){
return (top == NULL) ? 1 : 0;
}
void push(struct sNode** top_ref, int new_data){
struct sNode* new_node
= (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow \n");
exit(0);
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct sNode** top_ref){
char res;
struct sNode* top;
if (*top_ref == NULL) {
printf("Stack overflow \n");
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
void print(struct sNode* top){
printf("\n");
while (top != NULL) {
printf(" %d ", top->data);
top = top->next;
}
}
Program 15
C program to reverse a string using stack.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Stack {
int top;
unsigned capacity;
char* array;
};
struct Stack* createStack(unsigned capacity){
struct Stack* stack
= (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array
= (char*)malloc(stack->capacity * sizeof(char));
return stack;
}
int isFull(struct Stack* stack){
return stack->top == stack->capacity - 1;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
void push(struct Stack* stack, char item){
if (isFull(stack))
return;
stack->array[++stack->top] = item;
}
char pop(struct Stack* stack){
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
void reverse(char str[]){
int n = strlen(str);
struct Stack* stack = createStack(n);
int i;
for (i = 0; i < n; i++)
push(stack, str[i]);
for (i = 0; i < n; i++)
str[i] = pop(stack);
}
int main(){
char str[] = "GeeksQuiz";
reverse(str);
printf("Reversed string is %s", str);
return 0;
}
Program 16
Implementation of BFS for graph using Adjacency list.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
typedef struct Graph_t {
int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
Graph* Graph_create(int V){
Graph* g = malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
g->adj[i][j] = false;
}
}
return g;
}
void Graph_destroy(Graph* g) { free(g); }
void Graph_addEdge(Graph* g, int v, int w){
g->adj[v][w] = true;
}
void Graph_BFS(Graph* g, int s){
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
}
int queue[MAX_VERTICES];
int front = 0, rear = 0;
visited[s] = true;
queue[rear++] = s;
while (front != rear) {
s = queue[front++];
printf("%d ", s);
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}
int main(){
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
Printf(“following is Breadth First Traversal”
"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}
Program 17
C program to check if Binary tree is sum tree or not.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
int isLeaf(struct node *node){
if(node == NULL)
return 0;
if(node->left == NULL && node->right == NULL)
return 1;
return 0;
}
int isSumTree(struct node* node){
int ls; // for sum of nodes in left subtree
int rs; // for sum of nodes in right subtree
return true */
if(node == NULL || isLeaf(node))
return 1;
if( isSumTree(node->left) && isSumTree(node->right)){
if(node->left == NULL)
ls = 0;
else if(isLeaf(node->left))
ls = node->left->data;
else
ls = 2*(node->left->data);
if(node->right == NULL)
rs = 0;
else if(isLeaf(node->right))
rs = node->right->data;
else
rs = 2*(node->right->data);
return(node->data == ls + rs);
}
return 0;
}
struct node* newNode(int data){
struct node* node =
(struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main(){
struct node *root = newNode(26);
root->left = newNode(10);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(6);
root->right->right = newNode(3);
if(isSumTree(root))
printf("The given tree is a SumTree ");
else
printf("The given tree is not a SumTree ");
getchar();
return 0;
}
Program 18
C program to check if two Nodes in a binary tree are cousins.
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *left, *right;
};
struct Node *newNode(int item){
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
int isSibling(struct Node *root, struct Node *a, struct Node *b){
if (root==NULL) return 0;
return ((root->left==a && root->right==b)||
(root->left==b && root->right==a)||
isSibling(root->left, a, b)||
isSibling(root->right, a, b));
}
int level(struct Node *root, struct Node *ptr, int lev){
if (root == NULL) return 0;
if (root == ptr) return lev;
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
typedef struct Graph_t {
int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
Graph* Graph_create(int V){
Graph* g = malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
g->adj[i][j] = false;
}
}
return g;
}
void Graph_destroy(Graph* g) { free(g); }void Graph_addEdge(Graph* g, int v, int w){
// Add w to v’s list.
g->adj[v][w] = true;
}
void Graph_BFS(Graph* g, int s){
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
}
int queue[MAX_VERTICES];
int front = 0, rear = 0;
visited[s] = true;
queue[rear++] = s;
while (front != rear) {
s = queue[front++];
printf("%d ", s);
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}
int main(){
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
printf("Following is Breadth First Traversal "
"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}
Program 27
C Program for Depth First Search or DFS for a Graph.
#include <stdio.h>
#include <stdbool.h>
#define MAX_VERTICES 100
struct Graph {
bool visited[MAX_VERTICES];
int adj[MAX_VERTICES][MAX_VERTICES];
};
void addEdge(struct Graph* graph, int v, int w) {
graph->adj[v][w] = 1;
}
void DFS(struct Graph* graph, int v) {
graph->visited[v] = true;
printf("%d ", v);
for (int i = 0; i < MAX_VERTICES; ++i) {
if (graph->adj[v][i] == 1 && !graph->visited[i]) {
DFS(graph, i);
}
}
}
int main() {
struct Graph graph;
int i, j;
for (i = 0; i < MAX_VERTICES; ++i) {
graph.visited[i] = false;
for (j = 0; j < MAX_VERTICES; ++j) {
graph.adj[i][j] = 0;
}
}
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 1, 2);
addEdge(&graph, 2, 0);
addEdge(&graph, 2, 3);
addEdge(&graph, 3, 3);
printf("Following is Depth First Traversal (starting from vertex 2)\n");
DFS(&graph, 2);
return 0;
}
Program 28
C Program to Print matrix in zig-zag fashion.
#include <stdio.h>
#include<stdlib.h>
void zigZagMatrix(int arr[][C], int n, int m){
int row = 0, col = 0;
int row_inc = 0;
int mn = (m < n) ? m : n;
for (int len = 1; len <= mn; ++len) {
for (int i = 0; i < len; ++i) {
printf("%d ", arr[row][col]);
if (i + 1 == len)
break;
if (row_inc)
++row, --col;
else
--row, ++col;
}
if (len == mn)
break;
if (row_inc)
++row, row_inc = 0;
else
++col, row_inc = 1;
}
if (row == 0) {
if (col == m - 1)
++row;
Else{
++col;
row_inc = 1;
}
}
else {
if (row == n - 1)
++col;
Else{
++row;
row_inc = 0;
}
}
int MAX = (m > n) ? m : n;
for (int len, diag = MAX - 1; diag > 0; --diag) {
if (diag > mn)
len = mn;
else
len = diag;
for (int i = 0; i < len; ++i) {
if (i + 1 == len)
break;
if (row_inc)
++row, --col;
else
++col, --row;
}
if (row == 0 || col == m - 1) {
if (col == m - 1)
++row;
else
++col;
row_inc = 1;
}
else if (col == 0 || row == n - 1) {
if (row == n - 1)
++col;
else
++row;
row_inc = 0;
}
}
}
int main(){
int matrix[][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
zigZagMatrix(matrix, 3, 3);
return 0;
}
Program 29
C Program to find the scalar product of a matrix.
#include <stdio.h>
#include<stdlib.h>
void scalarProductMat(int mat[][N], int k){
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
mat[i][j] = mat[i][j] * k;
}
int main(){
int mat[N][N] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int k = 4;
scalarProductMat(mat, k);
printf("Scalar Product Matrix is : \n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
return 0;
}
Program 30
C Program to Delete a node in a Doubly Linked List.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void deleteNode(struct Node** head_ref, struct Node* del){
if (*head_ref == NULL || del == NULL)
return;
if (*head_ref == del)*head_ref = del->next;
if (del->next != NULL)
del->next->prev = del->prev;
if (del->prev != NULL)
del->prev->next = del->next;
free(del);
return;
}
void push(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
void printList(struct Node* node){
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main(){
struct Node* head = NULL;
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
printf("\n Original Linked list ");
printList(head);
deleteNode(&head, head); /*delete first node*/
deleteNode(&head, head->next); /*delete middle node*/
deleteNode(&head, head->next); /*delete last node*/
printf("\n Modified Linked list ");
printList(head);
getchar();
}