Unit 01

Arrays & Sorting Algorithms

Exp 01
Array Manipulation
Array Reverse
Aim

Write a C program to reverse all the elements in the array.

Input: First line contains integer N (size). Second line contains N space-separated integers.

Output: Print elements in reverse order.

Constraints: 1 ≤ N ≤ 1000, 0 ≤ arr[i] ≤ 1000

ArrayReverse.c
#include<stdio.h>

int main(){
        int a[20],n,i;
          scanf("%d",&n);
          for(i=0;i<n;i++)
          scanf("%d",&a[i]);
                  for(i=n-1;i>=0;i--)
                  printf("%d ",a[i]);
                   return 0;
}
All Test Cases Passed
Test Case 1
Input: 3 → 15 24 62 Output: 62 24 15
Test Case 2
Input: 4 → -54 63 -21 51 Output: 51 -21 63 -54
Test Case 3
Input: 5 → -50 -60 -70 100 80 Output: 80 100 -70 -60 -50
Test Case 5
Input: 5 → -5 -10 -15 -20 -25 Output: -25 -20 -15 -10 -5
Exp 02
Searching
Linear Search
Aim

Write a C program to check whether a given element is present in an array using linear search. Prompt the user for the size, elements, and search key. Output whether the element is found and at what 0-based index position.

Input: Size n (1≤n≤20), n integers, then search key.

Output: "Found at position X" (0-based) or "Y is not found"

SearchEle.c
#include<stdio.h>
int main(){
          int a[100],n,key,i,flag=0;
          printf("Enter size: ");
          scanf("%d",&n);
          printf("Enter %d element: ",n);
          for(i=0;i<n;i++){
                     scanf("%d",&a[i]);
          }
                     printf("Enter search element: ");
                     scanf("%d",&key);
                     for(i=0;i<n;i++)
                             {
                             if(a[i]==key)
                             {
                                     flag=1;
                                     break;
                             }
                             }
          if(flag==1)
          {
                                     printf("Found at position %d\n",i);
                             }
          else
                  printf("%d is not found\n",key);
          return 0;
}
All Test Cases Passed
Test Case 1
Enter size: 6 Enter 6 element: 2 4 8 1 3 5 Enter search element: 6 Output: 6 is not found
Test Case 2
Enter size: 6 Enter 6 element: 2 4 8 1 3 5 Enter search element: 2 Output: Found at position 0
Exp 03
Sorting
Bubble Sort
Aim

Write a C program that reads n integer numbers and arranges them in ascending order using the Bubble Sort algorithm. Display elements before and after sorting.

Input: Integer n (1≤n≤20), then n integers.

Output: "Before sorting: ..." then "After sorting: ..."

bubbleSort.c
#include<stdio.h>
void main()
{
        int a[20],i,n,j,temp;
        printf("n: ");
        scanf("%d",&n);
        printf("Elements: ");
        for(i=0;i<n;i++)
                {
                           scanf("%d",&a[i]);
                }
        printf("Before sorting: ");
        for(i=0;i<n;i++)
                {
                           printf("%d ",a[i]);
                }
        printf("\n");
        for(i=0;i<n-1;i++)
                {
                           for(j=0;j<n-1;j++)
                                   {
                                           if(a[j]>a[j+1])
                                          {
                                                   temp=a[j];
                                                   a[j]=a[j+1];
                                                   a[j+1]=temp;
                                          }
                                }
                }
        printf("After sorting: ");
        for(i=0;i<n;i++)
                {
                           printf("%d ",a[i]);
                }
        printf("\n");
}
All Test Cases Passed
Test Case 1
n: 4 Elements: 44 22 66 11 Before sorting: 44 22 66 11 After sorting: 11 22 44 66
Test Case 2
n: 5 Elements: 9 2 7 1 6 Before sorting: 9 2 7 1 6 After sorting: 1 2 6 7 9
Exp 04
Searching
Non-Recursive Binary Search
Aim

Write a C program that uses non-recursive functions to perform Binary Search for a Key value in a given sorted list of integers.

Input: Size (up to 20), sorted elements, search key.

Output: "found at X" (1-based) or "not found".

recursiveBinarySearch.c
#include <stdio.h>

int binarysearch(int arr[],int low,int high, int key) {
   while (low <= high){
              int mid = low + (high -low) / 2;
              if(arr[mid] == key) {
                      return mid;
              }
              if (arr[mid] < key) {
                      low = mid + 1;
              }
              else{
                      high = mid - 1;
              }
     }
     return -1;
}

int main() {
    int a[20], i, n, key, pos;
      printf("size: ");
      scanf("%d", & n);
      printf("elements: ");
      for (i = 0; i < n; i++) {
          scanf("%d", & a[i]);
      }
      printf("search element: ");
      scanf("%d", & key);
      pos = binarysearch(a, 0, n - 1, key);
      if (pos >= 0) {
          printf("found at %d", pos + 1);
      } else {
          printf("not found");
      }
}
All Test Cases Passed
Test Case 1
size: 3 elements: 3 6 9 search element: 6 Output: found at 2
Test Case 2
size: 3 elements: 3 6 9 search element: 2 Output: not found
Exp 05
Sorting
Insertion Sort
Aim

Write a C program that implements Insertion Sort to sort a given list of integers in ascending order.

Input: Integer n, then n integers.

Output: "Array before sort: ..." then "Array after insertion sort: ..."

insertionSort.c
#include<stdio.h>
void main()
{
          int a[100],n,i,j,ele;
          printf("Enter no of elements: ");
          scanf("%d",&n);
          printf("Enter the elements: ");
          for(i=0;i<n;i++)
                  scanf("%d",&a[i]);
          printf("Array before sort: ");
          for(i=0;i<n;i++)
                  printf("%d ",a[i]);
          printf("\n");
          for(i=0;i<n;i++)
                  {
                            ele=a[i];
                            for(j=i-1;j>=0;j--)
                                   {
                                            if(a[j]>ele)
                                            {
                                                    a[j+1]=a[j];
                                            }
                                            else
                                                    break;
                                   }
                            a[j+1]=ele;
                  }
          printf("Array after insertion sort: ");
          for(i=0;i<n;i++)
                  printf("%d ",a[i]);
          printf("\n");
}
All Test Cases Passed
Test Case 1
Enter no of elements: 6 Enter the elements: 1 5 4 2 6 8 Array before sort: 1 5 4 2 6 8 Array after insertion sort: 1 2 4 5 6 8
Test Case 2
Enter no of elements: 8 Enter the elements: 5 2 10 36 95 14 10 23 Array before sort: 5 2 10 36 95 14 10 23 Array after insertion sort: 2 5 10 10 14 23 36 95
Exp 06
Sorting
Selection Sort
Aim

Write a C program that implements the Selection Sort algorithm to sort a given list of integers in ascending order. Display elements before and after sorting.

Input: n (1≤n≤20), then n integers.

Output: "Array before sort: ..." then "Array after sort: ..."

selectionSort.c
#include<stdio.h>

void selectionSort(int arr[], int n) {
    int i, j, minIndex, temp;
    for(i=0;i<n;i++)
                {
                           for(j=0;j<n-1;j++)
                                  {
                                          if(arr[j]>arr[j+1])
                                          {
                                                  temp=arr[j];
                                                  arr[j]=arr[j+1];
                                                  arr[j+1]=temp;
                                          }
                                  }
                }
}

void main() {
        int n, i;
        printf("Enter no of elements: ");
        scanf("%d", &n);
        int arr[n];
        printf("Enter the elements: ");
        for(i = 0; i < n; i++) {
                scanf("%d", &arr[i]);
        }
        printf("Array before sort: ");
        for(i = 0; i < n; i++) {
                printf("%d ", arr[i]);
        }
        // Sorting the array using Selection Sort
        selectionSort(arr, n);
        printf("\nArray after sort: ");
        for(i = 0; i < n; i++) {
                printf("%d ", arr[i]);
        }
}
All Test Cases Passed
Test Case 1
Enter no of elements: 5 Enter the elements: 2 6 1 5 7 Array before sort: 2 6 1 5 7 Array after sort: 1 2 5 6 7
Test Case 2
Enter no of elements: 6 Enter the elements: 62 51 58 96 32 14 Array before sort: 62 51 58 96 32 14 Array after sort: 14 32 51 58 62 96
Test Case 3
Enter no of elements: 5 Enter the elements: 64 25 12 22 11 Array before sort: 64 25 12 22 11 Array after sort: 11 12 22 25 64
Unit 02

Singly Linked Lists & Polynomials

Exp 07
Singly Linked List
Insert at End & Traverse SLL
Aim

Write a C program to implement a single linked list that allows inserting elements at the end and displaying the elements. Implement: createNode(), insertAtEnd(NODE first, int x), traverseList(NODE first).

Output format: "The elements in SLL are : data1 --> data2 --> ... --> NULL" or "Single Linked List is empty"

SingleLL3.c (Driver)
#include<stdio.h>
#include<stdlib.h>

#include "InsAtEnding.c"

void main() {
        NODE first = NULL;
        int x, op;
        while(1) {
                printf("1.Insert At End 2.Traverse the List 3.Exit\n");
                printf("Enter your option : ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter an element : ");
                                        scanf("%d", &x);
                                           first = insertAtEnd(first, x);
                                           break;
                           case 2: if (first == NULL) {
                                                     printf("Single Linked List is empty\n");
                                          } else {
                                                     printf("The elements in SLL are : ");
                                                     traverseList(first);
                                          }
                                          break;
                           case 3: exit(0);
                }
        }
}
InsAtEnding.c
struct node {
int data;
struct node *next;
};
typedef struct node* NODE;
NODE createNode() {
NODE temp = (NODE) malloc(sizeof(struct node));
          temp->next= NULL;
                  return temp;
}

NODE insertAtEnd(NODE first, int x) {
          NODE temp = first;
          NODE newNode= (NODE) malloc(sizeof(struct node));
          newNode->data = x;
          newNode->next=NULL;
          if(temp==NULL)
                  return newNode;
          while(temp->next!=NULL)
                  temp = temp->next;
          temp->next=newNode;
          return first;
}

void traverseList(NODE first) {
        NODE temp=first;
          while(temp!=NULL)
                  {
                          printf("%d --> ",temp->data);
                          temp = temp->next;
                  }
          printf("NULL\n");
}
Exp 08
Singly Linked List
Insert at Begin & Delete at End in SLL
Aim

Fill in the missing code in insertAtBegin(NODE first, int x) and deleteAtEnd(NODE first) in InsAtBeginAndDelEnd.c.

SingleLL2.c (Driver)
#include<stdio.h>
#include<stdlib.h>

#include "InsAtBeginAndDelEnd.c"

void main() {
        NODE first = NULL;
        int x, op;
        while(1) {
                printf("1.Insert At Begin 2.Delete at End 3.Traverse the List 4.Exit\n");
                printf("Enter your option : ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter an element : ");
                                        scanf("%d", &x);
                                        first = insertAtBegin(first, x);
                                        break;
                        case 2:if (first == NULL) {
                                                   printf("Single Linked List is empty so deletion is not possible\n");
                                        } else {
                                                   first = deleteAtEnd(first);
                                        }
                                        break;
                        case 3: if (first == NULL) {
                                                   printf("Single Linked List is empty\n");
                                        } else {
                                                   printf("The elements in SLL are : ");
                                                   traverseList(first);
                                        }
                                        break;
                        case 4: exit(0);
                }
        }
}
InsAtBeginAndDelEnd.c
struct node {
        int data;
        struct node *next;
};
typedef struct node *NODE;
NODE deleteAtEnd(NODE first)
{
        NODE temp,prevnode;
        temp=first;
        while(temp->next!=0)
                {
                          prevnode=temp;
                          temp=temp->next;
                }
        if(temp==first)
        {
                first=0;
                printf("The deleted item from SLL : %d\n",temp->data);
                free(temp);
        }
        else{
                prevnode->next=0;
                printf("The deleted item from SLL : %d\n",temp->data);
                free(temp);
        }
        return first;
}

NODE createNode() {
        NODE newnode;
        newnode=(NODE)malloc(sizeof(struct node));
        return newnode;
}

NODE insertAtBegin(NODE first, int x) {
        NODE newnode,temp;
        newnode=createNode();
        newnode->data=x;
        newnode->next=0;
        if(first==0)
        {
                first=newnode;
        }
        else{
                newnode->next=first;
                first=newnode;
          }
          return first;
}

void traverseList(NODE first) {
        NODE temp = first;
          while (temp != NULL) {
                  printf("%d --> ",temp -> data);
                  temp = temp -> next;
          }
          printf("NULL\n");
}
Exp 09
Singly Linked List
Reverse a Singly Linked List
Aim

Write a C program to reverse the elements of a single linked list. Allow user to create a list of N nodes, reverse it, and display the reversed list.

Output: "Reversed the list: " followed by elements. If N ≤ 0, print "List size must be greater than zero:"

ReverseList.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void main()
{
          int i,n;
          struct node *newnode,*temp,*head,*prev,*nxt;
          printf("Enter no.of nodes: ");
          scanf("%d",&n);
          while(n<=0)
                 {
                 printf("List size must be greater than zero:\n");
                 printf("Enter no.of nodes: ");
                 scanf("%d",&n);
                 }
          head=0;
          printf("Enter data: ");
          for(i=1;i<=n;i++)
                 {
                          newnode=(struct node*)malloc(sizeof(struct node));
                          scanf("%d",&newnode->data);
                          newnode->next=0;
                          if(head==0)
                          {
                                  head=newnode;
                                    temp=newnode;
                          }
                          else{
                                    temp->next=newnode;
                                    temp=newnode;
                          }
                  }
          printf("Reversed the list: ");
          prev=0;
          temp=head;
          nxt=head;
          while(nxt!=0)
                  {
                          nxt=nxt->next;
                          temp->next=prev;
                            prev=temp;
                            temp=nxt;
                   }
           head=prev;
           temp=head;
           while(temp!=0)
                   {
                   printf("%d ",temp->data);
                   temp=temp->next;
                   }
}
All Test Cases Passed
Test Case 1
Enter no.of nodes: 4 Enter data: 1 2 3 4 Reversed the list: 4 3 2 1
Test Case 2
Enter no.of nodes: 0 List size must be greater than zero: Enter no.of nodes: 10 Enter data: 15 12 31 14 158 140 465 235 48 49 Reversed the list: 49 48 235 465 140 158 14 31 12 15
Exp 10
Singly Linked List
Reverse SLL Recursively
Aim

Write a C program to create a linked list, reverse it recursively, and display both the original and reversed linked lists.

Prompt with "No of nodes: ", then "Data for node X: " for each node. Print original then reversed list in "X -> Y -> Null" format.

RecursiveReverse.c
#include <stdio.h>
#include <stdlib.h>

struct Node {
     int data;
     struct Node* next;
};

// Write a function to create a new node with the given data
struct Node* createNode(int data) {
        struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
        newNode->data=data;
        newNode->next=NULL;
        return newNode;
}
// Write a function to print the linked list
void printList(struct Node* head) {
        while(head!=NULL){
                printf("%d -> ",head->data);
                head=head->next;
        }
        printf("Null\n");
}
// Write a function to reverse the linked list recursively
struct Node* reverseList(struct Node* current, struct Node* prev) {
        if(current==NULL){
                return prev;
        }
        struct Node*
        nextNode=current->next;
        current->next=prev;

        return reverseList(nextNode, current);
}
// Write your main function here
int main() {
    int n, data;

     // Getting the number of nodes from the user
     printf("No of nodes: ");
     scanf("%d", &n);

     // Creating the linked list based on user input
     struct Node* head = NULL;
     struct Node* tail = NULL;
        for (int i = 0; i < n; ++i) {
            printf("Data for node %d: ", i + 1);
            scanf("%d", &data);
            struct Node* newNode = createNode(data);
            if (head == NULL) {
                head = tail = newNode;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }

        printf("Original linked list: ");
        printList(head);

        // Reversing the linked list
        head = reverseList(head, NULL);

        printf("Reversed linked list: ");
        printList(head);

        // Freeing the allocated memory
        while (head != NULL) {
            struct Node* temp = head;
            head = head->next;
            free(temp);
        }

        return 0;
}
Exp 11
Singly Linked List
SLL Operations — Student Data (Menu Driven)
Aim

Write a C program for menu driven operations on Singly Linked List (SLL) of Student Data (USN, Name, Branch, Sem, PhNo):

  • 1. Create SLL of N Students (front insertion)
  • 2. Display status and count nodes
  • 3. Insert at End
  • 4. Delete at End
  • 5. Insertion/Deletion at Front (Stack demo)
  • 6. Exit
sll.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char U[25],N[25],B[25];
int S;
long long int P;
struct node* n;
};
struct node* IB(struct node*h){
struct node*nn=(struct node*)malloc(sizeof(struct node));
scanf("%s%s%s%d%lld",nn->U,nn->N,nn->B,&nn->S,&nn->P);
nn->n=h;
return nn;
}
struct node* IE(struct node* h){
        struct node* t=h;
        struct node* nn=(struct node*)malloc(sizeof(struct node));
        scanf("%s%s%s%d%lld",nn->U,nn->N,nn->B,&nn->S,&nn->P);
        nn->n=NULL;
        if(t==NULL)
                return nn;
        while(t->n!=NULL)
                t=t->n;
        t->n=nn;
        return h;
}
struct node* DE(struct node* h){
        struct node* t=h;
struct node* p=NULL;
        if(h==NULL){
                printf("Linked List is empty\n");
        return NULL;}
if(t->n==NULL){
        printf("The student node with usn: %s is deleted\n",t->U);
        free(t);
        return NULL;
}
        while(t->n!=NULL){
                p=t;
        t=t->n;}
                p->n=NULL;
        printf("The student node with usn: %s is deleted\n",t->U);
        free(t);
        return h;
}
        void D(struct node* h){
                  struct node* t=h;
                  int i=1;
while(t!=NULL){
                        printf("--%d-- USN:%s| Name:%s| Branch:%s| Sem:%d| Ph:%lld|\n",i,t->U,t->N,t->B,t->S,t->P);
                           t=t->n;
                           i++;
                  }
                  printf("No of student nodes is %d\n",i-1);
        }
struct node* DB(struct node* h){
        struct node *t=h;
        h=h->n;
        printf("The Student node with usn: %s is deleted\n",t->U);
        free(t);
        return h;
}
void main(){
        struct node* h=NULL;
        int i,ch,ch1,n;
        EAR:
        do{
                printf("1: Create SLL of Student Nodes\n2: DisplayStatus\n3: InsertAtEnd\n4: DeleteAtEnd\n5: Stack Demo using SLL(Insertion and Deletion at Front)\n6: Exit\nEnter your choice: ");
                scanf("%d",&ch);
                  switch(ch){
                          case 1:
                                     printf("Enter the no of students: ");
                                  scanf("%d",&n);
                  for(i=0;i<n;i++){
                          printf("Enter usn, Name, Branch, sem, PhoneNo of student: ");
                           h=IB(h);
                  }
                  break;
        case 2:
                  if(h==NULL)
                          printf("---No elements to display---\n");
                  else{
                           printf("The details of the students: \n");
                                   D(h);
                  }
                  break;
                 case 3:
                 printf("Enter usn, Name, Branch, sem, PhoneNo of student: ");
                           h=IE(h);
                           break;
                           case 4:
                           h=DE(h);
                           break;
                 case 5:
                           do{
                                printf("1: Push operation\n2: Pop operation\n3: Display\n4: Exit\nEnter your choice for stack demo: ");
                                     scanf("%d",&ch1);
                                             switch(ch1){
                                                     case 1:
                                                       printf("Enter usn, Name, Branch, sem, PhoneNo of student: ");
                                        h=IE(h);
                                             break;
                                             case 2:
                                          if(h==NULL)
          printf("Linked list is empty\n");
                  else
                           h=DB(h);
                                             break;
case 3:
                                                     if(h==NULL)
                                     printf("---No elements to display---\n");
                           else{
                                     printf("The details of the students:\n");
                                     D(h);
                           }
                                             break;
                                                       case 4:
                                             goto EAR;
                                             }
                                     }
                                     while(1);
                           break;
                           case 6:
                           exit(0);
                           }
          }
          while(1);
}
Exp 12
Singly Linked List
Remove Duplicate Elements in SLL
Aim

Write a program to remove all duplicate elements that are present in a given singly linked list.

Algorithm: Take input elements → Sort them → Traverse and compare each node with next → If data same, delete next node → Print result.

Input: Enter elements one by one, -1 to stop. Output: List before and after removing duplicates.

SingleLL10.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#include "RemoveLL.c"

int main() {
        NODE l1;
        l1 = NULL;
        printf("Enter list elements :\n");
        l1 = createAndAddNodes(l1);
        sort(l1);
        printf("List before removing duplicates : ");
        print(l1);
        printf("\n");
        printf("List after removing duplicates : ");
        removeDuplicates(l1);
        print(l1);
}
RemoveLL.c
struct node {
        int data;
        struct node *next;
};
typedef struct node * NODE;

NODE createAndAddNodes(NODE first) {
        NODE temp, q;
        int x;
        printf("Enter element : ");
        scanf("%d", &x);
        while(x != -1) {
                temp = (NODE)malloc(sizeof(struct node));
                temp->data = x;
                temp->next = NULL;
                if(first == NULL) {
                         first = temp;
                } else {
                           q->next = temp;
                }
                q = temp;
                printf("Enter element : ");
                scanf("%d", &x);
        }
        return first;
}
void print(NODE node) {
        while (node != NULL) {
                printf("%d ", node->data);
                node = node -> next;
        }
}
NODE sort(NODE first) {
        NODE t1, t2;
        int x;
        for(t1 = first; t1 -> next != NULL; t1 = t1 -> next) {
                for(t2 = t1 -> next; t2 != NULL; t2 = t2 -> next) {
                        if (t1 -> data > t2 -> data) {
                                x = t1 -> data;
                                  t1 -> data = t2 -> data;
                                  t2 -> data = x;
                           }
                }
        }
        return first;
}

NODE removeDuplicates(NODE head) {
        NODE current=head;
          NODE next_next;
          if(current==NULL)
                  return NULL;
          while(current->next!=NULL){
                  if(current->data==current->next->data){
                            next_next=current->next->next;
                            free(current->next);
                            current->next=next_next;
                  }
                  else{
                            current=current->next;
                  }
          }
          return head;
}
Exp 13
Polynomial — Linked List
Creating & Printing Polynomials Using Linked Lists
Aim

Fill in the missing code to create and print a polynomial using linked lists. Each node holds coeff and exp. Output: "coeff X^ exp ---> ... ---> NULL"

PolyLLMain.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#define max 20

#include "CreateAndPrintPolyLL.c"

poly create(poly head) {
        poly temp;
        char ch;
        int coeff, exp;
        do {
                 temp = (poly)malloc(sizeof(struct polynomial));
                 printf("Enter coeff and exp of node : ");
                 scanf("%d%d", &coeff, &exp);
                 temp -> coeff = coeff;
                 temp -> exp = exp;
                 temp -> next = NULL;
                 head = addTerm(head, temp);
                 printf("Do u want another node (y/n) : ");
                 scanf(" %c", &ch);
        } while(ch != 'n');
        return head;
}

void main() {
        poly head = NULL;
        int ch;
        head = create(head);
        printf("The polynomial is : ");
        print(head);
}
CreateAndPrintPolyLL.c
struct polynomial {
        int coeff;
        int exp;
        struct polynomial *next;
};
typedef struct polynomial *poly;

poly addTerm(poly head, poly temp) {
        poly p1,p2;
        p1=p2=head;
        if(p1==NULL){
                head=temp;
        }
        else{
                while(p1!=NULL&&p1->exp>temp->exp){
                          p2=p1;
                          p1=p1->next;
                }
                if(p1==NULL){
                        p2->next=temp;
                }
        else if(p1->exp==temp->exp){
                p1->coeff=p1->coeff+temp->coeff;
        }else if(p1->exp<temp->exp){
                if(p1==p2){
                        temp->next=p1;
                          head=temp;
                }else{
                          temp->next=p1;
                          p2->next=temp;
                }
        }
        }
        return head;
}

void print(poly head) {
        poly temp=head;
        while(temp!=NULL){
                printf("%d X^ %d ---> ",temp->coeff,temp->exp);
                temp=temp->next;
        }
        printf("NULL\n");
}
Exp 14
Polynomial — Linked List
Adding Polynomials Using Linked List
Aim

Write a C program to add two polynomials using linked lists. Create two polynomials, add them, and display all three.

PolyLLMain1.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#include "AddPolyLL.c"

poly create(poly head) {
        poly temp;
        char ch;
        int coeff, exp;
        do {
                temp = (poly)malloc(sizeof(struct polynomial));
                printf("Coeff and Power of the term: ");
                scanf("%d%d", &coeff, &exp);
                temp -> coeff = coeff;
                temp -> exp = exp;
                temp -> next = NULL;
                head = addTerm(head, temp);
                printf("Want to add more terms?(y/n): ");
                scanf(" %c", &ch);
        } while(ch != 'n');
        return head;
}

void main() {
        poly head1=NULL, head2= NULL, result = NULL;
        int ch;
        printf("First polynomial: \n");
        head1 = create(head1);
        printf("Second polynomial: \n");
        head2 = create(head2);
        result = add(head1, head2);
        printf("First polynomial: ");
        print(head1);
        printf("Second polynomial: ");
        print(head2);
        printf("Addition: ");
        print(result);
}
AddPolyLL.c
struct polynomial {
        int coeff;
        int exp;
        struct polynomial *next;
};
typedef struct polynomial *poly;

poly addTerm(poly head, poly temp) {
        poly p1,p2;
        p1=p2=head;
        if(p1==NULL){
                head=temp;
        }else{
                 while(p1!=NULL&&p1->exp>temp->exp){
                         p2=p1;
                         p1=p2->next;
                 }
                 if(p1==NULL){
                         p2->next=temp;
                 }else if(p1->exp==temp->exp){
                         p1->coeff=p1->coeff+temp->coeff;
                 }else if(p1->exp<temp->exp){
                         if(p2==p1){
                                   temp->next=p1;
                                   head=temp;
                          }
                          else{
                                   temp->next=p1;
                                   p2->next=temp;
                          }
                 }
        }
        return head;
}

void print(poly head) {
        poly temp=head;
        int isFirstTerm=1;
        while(temp!=NULL){
                if(temp->next!=NULL){
                        printf("%d X^%d",temp->coeff,temp->exp);
                          if(temp->next->coeff>0){
                                  printf(" + ");
                          }
                 }else{
                printf("%d X^%d",temp->coeff,temp->exp);
                }
                temp=temp->next;
        }
        printf("\n");
}

poly add(poly head1, poly head2) {
        poly t1,t2,sum=NULL,temp=NULL;
        t1=head1;
        t2=head2;
        while(t1!=NULL&&t2!=NULL){
                temp=(poly)malloc(sizeof(struct polynomial));
                if(t1->exp==t2->exp){
                        temp->coeff=t1->coeff+t2->coeff;
                        temp->exp=t1->exp;
                          temp->next=NULL;
                          sum=addTerm(sum,temp);
                        t1=t1->next;
                        t2=t2->next;
                }else if(t1->exp>t2->exp){
                          temp->coeff=t1->coeff;
                          temp->exp=t1->exp;
                          temp->next=NULL;
                                  sum=addTerm(sum,temp);
                          t1=t1->next;
                } else{
                          temp->coeff=t2->coeff;
                          temp->exp=t2->exp;
                          temp->next=NULL;
                          sum=addTerm(sum,temp);
                          t2=t2->next;
                }
        }
        while(t1!=NULL){
                temp=(poly)malloc(sizeof(struct polynomial));
                temp->coeff=t1->coeff;
                temp->exp=t1->exp;
                temp->next=NULL;
                sum=addTerm(sum,temp);
                t1=t1->next;
        }
        while(t2!=NULL){
                  temp=(poly)malloc(sizeof(struct polynomial));
                  temp->coeff=t2->coeff;
                  temp->exp=t2->exp;
                  temp->next=NULL;
                  sum=addTerm(sum,temp);
                  t2=t2->next;
          }
          return sum;
}
Unit 03

Doubly & Circular Linked Lists

Exp 15
Doubly Linked List
Insert at End & Traverse DLL
Aim

Fill in the missing code in insertAtEndInDLL(NODE first, int x) and traverseListInDLL(NODE first). The insert function adds to end; traverse prints all elements with "<-->".

DoubleLL1.c (Driver)
#include<stdio.h>
#include<stdlib.h>

#include "InsertEndAndTraverseInDLL.c"

void main() {
        NODE first = NULL;
        int x, op;
        while(1) {
                printf("1.Insert At End 2.Traverse the List 3.Exit\n");
                printf("Enter your option : ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter an element : ");
                                        scanf("%d", &x);
                                         first = insertAtEndInDLL(first, x);
                                         break;
                        case 2: if (first == NULL) {
                                                printf("Double Linked List is empty\n");
                                         } else {
                                                    printf("The elements in DLL are : ");
                                                    traverseListInDLL(first);
                                         }
                                         break;
                        case 3: exit(0);
                }
        }
}
InsertEndAndTraverseInDLL.c
struct node {
        int data;
        struct node *prev;
        struct node *next;
};
typedef struct node * NODE;

NODE createNodeInDLL() {
        NODE temp;
        temp = (NODE)malloc(sizeof(struct node));
        temp->prev = NULL;
        temp->next = NULL;
        return temp;
}

NODE insertAtEndInDLL(NODE first, int x) {
        NODE temp,last;
        temp=createNodeInDLL();
        temp->data=x;
        if(first==NULL){
                 first=temp;
        }else{
                 last=first;
                 while(last->next!=NULL){
                         last=last->next;
                 }
                 last->next=temp;
                 temp->prev=last;
        }
        return first;
}

void traverseListInDLL(NODE first) {
        if(first==NULL){
                 printf("List is empty \n");
                 return;
        }
        while(first!=NULL){
                printf("%d <--> ",first->data);
                first=first->next;
        }
        printf("NULL\n");
}
Exp 16
Doubly Linked List
All DLL Operations (Insert/Delete Begin, Search, Traverse)
Aim

Write a C program to implement a DLL with: Insert at beginning, Delete first element, Search for an element (return position), Traverse/display the list, Exit.

AllOperationsDLL.c
#include<stdio.h>
#include<stdlib.h>
struct node {
        int data;
        struct node *prev;
        struct node *next;
};

typedef struct node * NODE;
NODE createNodeInDLL() {
                NODE nn;
        nn=(NODE)malloc(sizeof(NODE));
        nn->next=0;
        nn->prev=0;
        return nn;
}

void traverseListInDLL(NODE first) {
                NODE nn=first;
        while(nn!=0) {
        printf("%d <--> ",nn->data);
        nn=nn->next;
        }
        printf("NULL\n");
}

NODE insertAtBeginInDLL(NODE first, int x) {
                NODE nn=createNodeInDLL();
        nn->data=x;
        nn->next=0;
        nn->prev=0;
        if(first!=0) {
        nn->next=first;
        first->prev=nn;
        }
        first=nn;
return first;
}

int searchPosOfEleInDLL(NODE first, int element) {
                NODE nn=first;
        int pos=0;
        if(first==0)
         return 0;
         while(nn!=0 && nn->data!=element) {
         if(nn->next==0)
         return 0;
         pos++;
         nn=nn->next;
         }
         return pos+1;
}

NODE deleteAtBeginInDLL(NODE first) {
        NODE lastNode,nn;
         nn=first;
         if(nn->next==0)
         first=0;
         else{
         first=first->next;
         first->prev=0;
         }
         lastNode=nn;
         printf("The deleted element from DLL : %d\n", lastNode -> data);
         free(lastNode);
         return first;
}
void main() {
        NODE first = NULL;
         int x, pos, op;
         while(1) {
                 printf("1.Insert At Begin\n2.Delete at Begin\n3.Search an element Position\n4.Traverse the List\n5.Exit\n");
                printf("Enter your option : ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter an element: ");
                                        scanf("%d", &x);
                                        first = insertAtBeginInDLL(first, x);
                                        break;
                           case 2:
                                        if (first == NULL) {
                                                   printf("Double Linked List is empty so deletion is not possible\n");
                                        } else {
                                                   first = deleteAtBeginInDLL(first);
                                             }
                                             break;
                           case 3:
                                             printf("Enter search element: ");
                                             scanf("%d", &x);
                                             pos = searchPosOfEleInDLL(first, x);
                                             if (pos == 0) {
                                                        printf("The given element %d is not found in the given DLL\n", x);
                                             } else {
                                                printf("The given element %d is found at position : %d\n", x, pos);
                                             }
                                             break;
                           case 4:
                                             if (first == NULL) {
                                                     printf("Double Linked List is empty\n");
                                             } else {
                                                        printf("The elements in DLL are: ");
                                                        traverseListInDLL(first);
                                             }
                                             break;
                           case 5: exit(0);
                   }
             }
}
Exp 17
Doubly Linked List
DLL Operations — Employee Data (Menu Driven)
Aim

Write a menu-driven C program for DLL operations on Employee Data (SSN, Name, Dept, Designation, Salary, PhNo):

  • 1. Create DLL of N Employees (end insertion)
  • 2. Display status and count
  • 3. Insert/Delete at End
  • 4. Insert/Delete at Front
  • 5. Exit
dllOps.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char ssn[6];
char name[20];
char department[20];
char designation[20];
long long salary;
long long phno;
struct node *prev;
struct node *next;
};
struct node* insertatend(int n, struct node *tail);
void display(struct node *head);
struct node* deleteatend(struct node *tail);
struct node* insertatfront(struct node *head);
struct node* deleteatfront(struct node *head);

void main() {
        int ch, n;
        struct node *head = NULL, *tail = NULL;
        while(1) {
                printf("1: Create DLL of Employee Nodes\n2: DisplayStatus\n3: InsertAtEnd\n4: DeleteAtEnd\n5: InsertAtFront\n6: DeleteAtFront\n7: Exit\nPlease enter your choice: ");
                scanf("%d", &ch);
                switch (ch) {
                        case 1:
                        printf("Enter no of Employees: ");
                        scanf("%d", &n);
                        if (n <= 0) {
                                printf("Number of employees should be positive\n");
                                break;
                        }
                        if (head == NULL) {
                                head = (struct node*)malloc(sizeof(struct node));
                                printf("Enter ssn, Name, Department, Designation, Salary, PhoneNo of employee: ");
                                scanf("%s %s %s %s %lld %lld", head->ssn, head->name, head->department, head->designation, &head->salary, &head->phno);
                                head->prev = NULL;
                                head->next = NULL;
                                tail = head;
                                tail = insertatend(n - 1, tail);
                        } else {
                                tail = insertatend(n, tail);
                        }
                        if (tail == NULL)
                                  head = tail;
                        break;
                        case 2:
                        if (head == NULL)
                                printf("DLL is Empty\n");
                        else
                                  display(head);
                        break;
                        case 3:
                        if (head == NULL) {
                                head = (struct node*)malloc(sizeof(struct node));
                                printf("Enter ssn, Name, Department, Designation, Salary, PhoneNo of employee: ");
                                scanf("%s %s %s %s %lld %lld", head->ssn, head->name, head->department, head->designation, &head->salary, &head->phno);
                                  head->prev = NULL;
                                  head->next = NULL;
                                tail = head;
                        } else {
                                tail = insertatend(1, tail);
                        }
                        break;
                        case 4:
                        if (head == NULL) {
                                printf("DLL is empty\n");
                        } else {
                                tail = deleteatend(tail);
                                if (tail == NULL)
                                         head = tail;
                        }
                        break;
                        case 5:
                        if (head == NULL) {
                                head = insertatfront(head);
                                tail = head;
                        } else {
                                  head = insertatfront(head);
                        }
                        break;
                        case 6:
                           if (head == NULL) {
                                   printf("DLL is empty\n");
                           } else {
                                   head = deleteatfront(head);
                                   if (head == NULL)
                                           tail = head;
                           }
                           break;
                           case 7:
                           exit(0);
                           break;
                           default:
                           printf("Please Enter valid choice\n");
                           break;
                   }
        }
}

struct node* insertatend(int n, struct node *tail) {
        int i;
        struct node *newnode;
        for (i = 1; i <= n; i++) {
                newnode = (struct node*)malloc(sizeof(struct node));
                printf("Enter ssn, Name, Department, Designation, Salary, PhoneNo of employee: ");
                scanf("%s %s %s %s %lld %lld", newnode->ssn, newnode->name, newnode->department, newnode->designation, &newnode->salary, &newnode->phno);
                           newnode->next = NULL;
                   newnode->prev = tail;
                   tail->next = newnode;
                   tail = newnode;
        }
        return tail;
}
void display(struct node *head) {
        int len = 0;
        struct node *temp;
        temp = head;
        while (temp != NULL) {
                printf("SSN:%s| Name:%s| Department:%s| Designation:%s| Salary:%lld| Phone no:%lld\n", temp->ssn, temp->name, temp->department, temp->designation, temp->salary, temp->phno);
                   len++;
                   temp = temp->next;
        }
        printf("No of employees: %d\n", len);
}

struct node* deleteatend(struct node *tail) {
        struct node *temp;
        if (tail == NULL) {
                printf("DLL is empty\n");
                return NULL;
        }
        temp = tail;
        if (tail->prev != NULL) {
                tail = tail->prev;
                tail->next = NULL;
        } else {
                tail = NULL;
        }
        printf("employee with ssn: %s is deleted\n", temp->ssn);
        free(temp);
        return tail;
}
struct node* insertatfront(struct node *head) {
        struct node *newnode;
        newnode = (struct node*)malloc(sizeof(struct node));
        printf("Enter ssn, Name, Department, Designation, Salary, PhoneNo of employee: ");
        scanf("%s %s %s %s %lld %lld", newnode->ssn, newnode->name, newnode->department, newnode->designation, &newnode->salary, &newnode->phno);
        if (head == NULL) {
                head = newnode;
                head->next = NULL;
                head->prev = NULL;
        } else {
                newnode->next = head;
                newnode->prev = NULL;
                head->prev = newnode;
                head = newnode;
        }
        return head;
}
struct node* deleteatfront(struct node *head) {
        struct node *temp;
        if (head == NULL) {
                printf("DLL is empty\n");
                return NULL;
        }
        temp = head;
        head = head->next;
          if (head != NULL)
                  head->prev = NULL;
          printf("employee with ssn: %s is deleted\n", temp->ssn);
          free(temp);
          return head;
}
Exp 18
Circular Linked List
insertAtBeginInCLL() and countInCLL()
Aim

Fill in the missing code in insertAtBeginInCLL(NODE first, int x) and countInCLL(NODE first). Insert inserts at beginning of CLL; count counts nodes in CLL.

CircularLL2.c (Driver)
#include <stdio.h>
#include <stdlib.h>

#include "InsAtBeginAndCountInCLL.c"

void main() {
        NODE first = NULL;
        int x, op;
        while(1) {
                printf("1.Insert At Begin 2.Count Number of Nodes 3.Traverse the List 4.Exit\n");
                printf("Enter your option : ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter an element : ");
                                       scanf("%d", &x);
                                       first = insertAtBeginInCLL(first, x);
                                        break;
                        case 2: printf("The number of nodes in a CLL are : %d\n", countInCLL(first));
                                        break;
                        case 3: if (first == NULL) {
                                                  printf("Circular Linked List is empty\n");
                                       } else {
                                                  printf("The elements in CLL are : ");
                                                  traverseListInCLL(first);
                                       }
                                        break;
                        case 4: exit(0);
                }
        }
}
InsAtBeginAndCountInCLL.c
struct node {
        int data;
        struct node *next;
};
typedef struct node *NODE;

NODE createNodeInCLL() {
        NODE temp;
        temp = (NODE) malloc(sizeof(struct node));
        temp -> next = NULL;
        return temp;
}

NODE insertAtBeginInCLL(NODE first, int x) {
        NODE newnode,temp;
        newnode=(NODE)malloc(sizeof(NODE));
        newnode->data=x;
        temp=first;
        while(temp->next!=first)
                {
                           temp=temp->next;
}
        newnode->next=first;
        temp->next=newnode;
        first=newnode;
        return first;
}
int countInCLL(NODE first) {
        NODE temp;
        int cnt=0;
        temp=first;
        while(temp->next!=first)
                {
                        cnt++;
                           temp=temp->next;
                }
        return cnt;
}

void traverseListInCLL(NODE first) {
        NODE temp = first;
        do {
                printf("%d --> ", temp -> data);
                temp = temp -> next;
        } while (temp->next != first);
          printf("\n");
}
Exp 19
Circular Linked List
All CLL Operations (Create, Insert, Delete, Traverse)
Aim

Write a program to perform all operations on Circular Linked List: Creation, Insertion at position, Deletion at position, Traversal.

AlloperationsinCLL.c
#include<stdio.h>
#include<stdlib.h>

struct node {
        int data;
        struct node *next;
};
typedef struct node *NODE;

NODE createNodeInCLL() {
        NODE temp;
        temp= (NODE)malloc(sizeof(struct node));
        temp-> next = NULL;
        return temp;
}

NODE insertAtPositionInCLL(NODE first, int pos, int x) {
        NODE temp,lastNode=first;
        int i;
        for(i=1; i<pos-1;i++) {
                if(lastNode->next==first){
                        printf("No such position in CLL so insertion is not possible\n");
                         return first;
                 }
                 lastNode=lastNode->next;
        }
        temp=createNodeInCLL();
        temp->data=x;
        if(pos==1){
                if(first==NULL){
                           first=temp;
                           temp->next=first;
                 }
                 else{
                           while(lastNode->next!=first){
                                   lastNode=lastNode->next;
                           }
                           temp->next=first;
                           first=temp;
                           lastNode->next=first;
                 }
        }else{
                 temp->next=lastNode->next;
                 lastNode->next=temp;
        }
         return first;
}

NODE deleteAtPositionInCLL(NODE first, int pos) {
         NODE prev=first,lastNode=first;
         int i;
         if(pos==1){
                if(prev->next==first){
                        first=NULL;
                }else{
                         while(lastNode->next!=first){
                                 lastNode=lastNode->next;
                         }
                         first=prev->next;
                         lastNode->next=first;
                }
}else{
         for(i=1;i<pos;i++){
                if(prev->next==first){
                                printf("No such position in CLL so deletion is not possible\n");
                                   return first;
                }
                lastNode=prev;
                prev=prev->next;
         }
         lastNode->next=prev->next;
}
         printf("The deleted element from CLL : %d\n", prev -> data);
         free(prev);
         return first;
}

void traverseListInCLL(NODE first) {
         NODE temp = first;
         do{
                printf("%d --> ",temp ->data);
                temp = temp -> next;
         }
         while(temp != first);
         printf("\n");
}

void main() {
         NODE first = NULL;
         int x, pos, op;
        while(1) {
                printf("1.Insert 2.Delete 3.Print 4.Exit\n");
                printf("Enter your option: ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter a position: ");
                                        scanf("%d", &pos);
                                        if (pos <= 0) {
                                                printf("No such position in CLL so insertion is not possible\n");
                                        } else {
                                                   printf("Enter an element: ");
                                                   scanf("%d", &x);
                                                   first = insertAtPositionInCLL(first, pos, x);
                                        }
                                        break;
                case 2: if (first == NULL) {
                                                   printf("Circular Linked List is empty so deletion is not possible\n");
                                        } else {
                                                   printf("Enter position : ");
                                                   scanf("%d", &pos);
                                                   first = deleteAtPositionInCLL(first, pos);
                                        }
                                        break;
                        case 3: if (first == NULL) {
                                                printf("Circular Linked List is empty\n");
                                        } else {
                                                   printf("The elements in CLL are: ");
                                                   traverseListInCLL(first);
                                        }
                                        break;
                        case 4: exit(0);
                }
        }
}
Exp 20
Double-Ended Queue
DEQueue Using Linked List — inject, eject, display
Aim

Implement a double-ended queue using linked list. Fill missing code in inject(int ele), eject(), and display().

  • inject(ele): insert at rear; print "Dequeue is overflow." if full
  • eject(): remove from rear; print "Dequeue is underflow." if empty
  • display(): print all elements
DequeueListMain1.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#include "DequeueListInjectEject.c"
int main() {
    int op, x;
    while (1) {
      printf("1.Inject 2.Eject 3.Display 4.Exit\n");
        printf("Enter your option : ");
        scanf("%d", & op);
        switch (op) {
        case 1:
          printf("Enter element : ");
            scanf("%d", & x);
            inject(x);
            break;
        case 2:
          eject();
          break;
        case 3:
          display();
          break;
        case 4:
          exit(0);
        }
    }
}
DequeueListInjectEject.c
struct queue {
        int data;
          struct queue *next;
};
typedef struct queue *DeQueue;
DeQueue front = NULL, rear = NULL;

void inject(int ele) {
        DeQueue temp=NULL;
        temp=(DeQueue)malloc(sizeof(struct queue));
          if(temp==NULL){
                  printf("Deueue is overflow.\n");
          }
          else{
                  temp->data=ele;
                  temp->next=NULL;
                  if(front==NULL){
                          front=temp;
                  }
                  else{
                          rear->next=temp;
                  }
                  rear=temp;
                  printf("Successfully inserted at rear side.\n");
          }
}
void eject() {
        DeQueue temp=NULL;
          if(rear==NULL){
                  printf("Dequeue is underflow.\n");
          }else{
                  temp=front;
                  if(front==rear){
                          front=rear=NULL;
                  }
                  else{
                          while(temp->next!=rear){
                                  temp=temp->next;
                          }
                          rear=temp;
                          temp=rear->next;
                          rear->next=NULL;
                  }
                  printf("Deleted element %d from the rear side.\n",temp->data);
                  free(temp);
          }
}
void display() {
        if(front==NULL){
                  printf("Double ended queue is empty.\n");
          }
          else{
                  DeQueue temp=front;
                  printf("Elements in the double ended queue : \n");
                  while(temp!=NULL){
                           printf("%d ",temp->data);
                           temp=temp->next;
                  }
                  printf("\n");
          }
}
Unit 04

Stacks — Arrays, Linked Lists & Applications

Exp 21
Stack
Stack Using Arrays (Push, Pop, Display, isEmpty, Peek)
Aim

Write a C program to implement stack operations using arrays. Menu: Push, Pop, Display, Is Empty, Peek, Exit. Max size = 10.

StackUsingArray.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX_SIZE 10
#include "StackOperations.c"

int main() {
        int op, x;
        while(1) {
                printf("1.Push 2.Pop 3.Display 4.Is Empty 5.Peek 6.Exit\n");
                printf("Option: ");
                scanf("%d", &op);
                switch(op) {
                        case 1:
                                  printf("element: ");
                                  scanf("%d", &x);
                                  push(x);
                                  break;
                        case 2:
                                  pop();
                                  break;
                        case 3:
                                  display();
                                  break;
                        case 4:
                                  isEmpty();
                                  break;
                        case 5:
                                  peek();
                                  break;
                        case 6:
                                  exit(0);
                }
        }
}
StackOperations.c
#define STACK_MAX_SIZE 10
int st[STACK_MAX_SIZE];
int top=-1;
void push(int element) {
                if( top==STACK_MAX_SIZE-1 )
                printf("Stack is overflow\n");
        else
        {
                top++;
                st[top]=element;
                printf("Successfully pushed\n");
        }
}
void display() {
        if( top==-1)
                printf("Stack is empty\n");
        else
        {
                printf("Elements: ");
                for(int i=top;i>=0;i-- )
                        printf("%d ",st[i]);
                printf("\n");
        }
}

void pop() {
        if( top==-1 )
                printf("Stack is underflow\n");
        else
        {
                printf("Popped value: %d\n",st[top]);
                top--;
        }
}
void peek(){
        if( top==-1 )
printf("Stack is underflow\n");
else
printf("Peek value: %d\n",st[top]);
}
void isEmpty() {
        if(top==-1)
printf("Stack is empty\n");
else
printf("Stack is not empty\n");
}
Exp 22
Stack
Stack Using Linked Lists
Aim

Write a program to implement a stack using linked lists. Menu: Push, Pop, Display, Is Empty, Peek, Exit. Outputs: "Successfully pushed.", "Popped value = X", "Stack is underflow.", "Stack is empty.", "Stack is not empty.", "Peek value = X"

StackUsingLL.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#include "StackOperationsLL.c"

int main() {
          int op, x;
          while(1) {
                   printf("1.Push 2.Pop 3.Display 4.Is Empty 5.Peek 6.Exit\n");
                   printf("Enter your option : ");
                   scanf("%d", &op);
                   switch(op) {
                           case 1:
                                       printf("Enter element : ");
                                       scanf("%d", &x);
                                       push(x);
                                       break;
                             case 2:
                                       pop();
                                       break;
                             case 3:
                                       display();
                                       break;
                             case 4:
                                       isEmpty();
                                       break;
                             case 5:
                                       peek();
                                       break;
                             case 6:
                                       exit(0);
                   }
          }
}
StackOperationsLL.c
struct stack
{
int data;
struct stack *next;
};
struct stack *top = NULL;

void push(int val)
{
        struct stack *ptr;
        ptr=top;
        ptr=(struct stack *)malloc(sizeof(struct stack));
        ptr->data = val;
        if(top==NULL)
        {
                ptr->next=NULL;
                top=ptr;
                printf("Successfully pushed.\n");
        }
        else{
                ptr->next=top;
                top=ptr;
                printf("Successfully pushed.\n");
        }
}
void pop()
{
        struct stack *ptr;
        ptr=top;
        if(top==NULL)
                printf("Stack is underflow.\n");
        else{
                top=top->next;
                printf("Popped value = %d\n",ptr->data);
                free(ptr);
        }
}
void display()
{
        struct stack *ptr;
        ptr=top;
        if(top==NULL)
        {
                printf("Stack is empty.\n");
        }
        else{
                printf("Elements of the stack are : ");
                while(ptr!=NULL)
                        {
                                  printf("%d ",ptr->data);
                                  ptr=ptr->next;
                        }
                  printf("\n");
          }
}
void isEmpty()
{
          if(top==NULL)
          {
                  printf("Stack is empty.\n");
          }
          else{
                  printf("Stack is not empty.\n");
          }
}
void peek()
{
          if(top==NULL)
                  printf("Stack is underflow.\n");
          else
                  printf("Peek value = %d\n",top->data);
}
Exp 23
Stack Application
Evaluate a Postfix Expression
Aim

Write a C program to evaluate a postfix expression using a stack. Write isEmpty(), push(int x), pop() and evaluatePostfix(char *e).

Input: Postfix expression string (digits 0-9 and operators +,-,*,/,%). Output: "Result : r" or "Invalid postfix expression."

PostfixEvaluation.c
#include <ctype.h>
#include <stdio.h>
#define STACK_MAX_SIZE 20
//Declare the required stack variables.
int a[STACK_MAX_SIZE];
int top=-1;
//Return 1 if stack is empty else return 0.
int isEmpty() {
        if(top<0)
                return 1;
        else
                return 0;
}

//Push the character into stack
void push(int x) {
        top++;
         a[top]=x;
}

//pop a character from stack
int pop() {
        return a[top--];
}

//Output Format - Result : <r> if the input postfix expression is valid.
//Output Format - Invalid postfix expression. - if the input expression is invalid.
//postfix expression is given as the parameter.
void evaluatePostfix(char * e) {
        int a,b,i;
        i=0;
        while(e[i]!='\0')
                {
                        if (isdigit(e[i]))
                        {
                                  push(e[i]-'0');
                        }
                        else
                        {
                                  if(top<0)
                                  {
                                          break;
                                  }
                                  b=pop();
                                     a=pop();
                                     switch(e[i])
                                             {
                                                     case '+':push(a+b);
                                                             break;
                                                     case '-':push(a-b);
                                                             break;
                                                     case '*':push(a*b);
                                                             break;
                                                     case '/':push(a/b);
                                                              break;
                                             }
                            }
                            i++;
                   }
            if(!isEmpty()&&top==0)
            {
                    printf("Result : %d\n",pop());
            }
            else
            {
                   printf("Invalid postfix expression.\n");
            }
}

//Read a postfix expression and evaluate it.
int main() {
        char exp[20];
            char *e, x;
            printf("Enter the postfix expression : ");
            scanf("%s",exp);
            e = exp;
            evaluatePostfix(e);
}
All Test Cases Passed
Test Case 1
Enter the postfix expression: 234+- Result : -5
Test Case 2
Enter the postfix expression: -456+5+ Invalid postfix expression.
Exp 24
Stack Application
Balanced Parenthesis Check Using Stack
Aim

Write a C program to check if parentheses in a given expression are balanced. Recognises (), {}, []. Output: "balanced" or "not balanced".

BalancedParenthesis.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define STACK_MAX_SIZE 30
char arr[STACK_MAX_SIZE];
int top = -1;
void push(char element) {
        if(top==STACK_MAX_SIZE -1 ) {
                printf("Stack is overflow.\n");
        }else{
                 top = top + 1;
                 arr[top] = element;
        }
}

char pop() {
        long int x;
        if(top < 0)
        {
                 printf("Stack is overflow.\n");
                 return - 1;
        }else{
                 x = arr[top];
                 top = top -1;
                 return x;
        }
}

int isempty() {
        if(top == -1)
        return 1;
        else
        return 0;
}

int isBalanced(char exp[]) {
        int i,n;
        char x;
        n = strlen(exp);
        for(i=0;i<n;i++)
                {
                           if(exp[i]=='('||exp[i]=='{'||exp[i]=='[')
                           {
                                  push(exp[i]);
                        }
else if(exp[i]=='}'||exp[i]==']'||exp[i]==')')
                           {
                                  if(isempty())
                                          return 0;
                                  x=pop();
                                  if((exp[i] == ')' && x != '(')||(exp[i] == '}' && x != '{')||
                                          (exp[i] == ']' && x != '[')) {
                                          return 0;
                                          }
                           }
          }
          return isempty();
}

void main() {
          char ch[80], temp;
          printf("Enter an expression: ");
          scanf("%s", ch);
          if(isBalanced(ch) == 1) {
                  printf("balanced\n");
          } else {
                  printf("not balanced\n");
          }
}
All Test Cases Passed
Test Case 1
Enter an expression: 1+2*3+(3+4) Output: balanced
Test Case 2
Enter an expression: 1+2*(3+([4+5]) Output: not balanced
Unit 05

Queues & Applications

Exp 25
Queue
Queue Operations Using Static Array (Circular)
Aim

Write a program to implement queue operations using static arrays (MAX=10). Menu: Enqueue, Dequeue, Display, Is Empty, Size, Exit.

QueueUsingArray.c (Driver)
#include <stdlib.h>
#include <stdio.h>
#include "QueueOperations.c"
int main() {
        int op, x;
        while(1) {
                printf("1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Size 6.Exit\n");
                printf("Enter your option : ");
                scanf("%d",&op);
                switch(op) {
                        case 1:
                                  printf("Enter element : ");
                                  scanf("%d",&x);
                                  enqueue(x);
                                  break;
                        case 2:
                                  dequeue();
                                  break;
                        case 3:
                                  display();
                                  break;
                        case 4:
                                  isEmpty();
                                  break;
                        case 5:
                                  size();
                                  break;
                        case 6: exit(0);
                }
        }
        return 0;
}
QueueOperations.c
#define MAX 10
int queue[MAX];
int front = -1, rear = -1;

void enqueue(int x) {
                if(((rear==MAX-1) && (front==0)) || (rear+1==front)){
                printf("Queue is overflow.\n");
        }
        else{
                   if(rear==MAX-1){
                            rear=-1;
                   }
                   else if(front==-1){
                           front=0;
                   }
                   rear++;
                   queue[rear]=x;
                   printf("Successfully inserted.\n");
        }
}

void dequeue() {
                   if(front==-1){
                   printf("Queue is underflow.\n");
        }
        else{
                   printf("Deleted element = %d\n",queue[front]);
                                      if(rear==front){
rear=front=-1;
                                   }
                   else if(front ==MAX-1){
                           front=0;
                   }else{
                            front++;
                   }
        }
}

void display() {
                   int i;
        if(front==-1&&rear==-1){
                printf("Queue is empty.\n");
        }
                   else{
                   printf("Elements in the queue : ");
                   if(front<=rear){
                           for(i=front ;i<=rear;i++){
                                     printf("%d ",queue[i]);
                           }
                   }
                   else{
                           for(i=front;i<=MAX-1;i++)
                                   {
                                             printf("%d ",queue[i]);
                                     }
                   }
                   printf("\n");
        }
}

void size() {
        if(front == -1 && rear == -1)
                printf("Queue size : 0\n");
                   else{
                   if(front<=rear){
                   printf("Queue size : %d\n",rear-front+1);
                   }
                                             else{
                                     printf("Queue size : %d\n",MAX-front+rear+1);
                           }
}
}

void isEmpty() {
        if(front==-1&&rear==-1)
                printf("Queue is empty.\n");
                   else
                   printf("Queue is not empty.\n");
}
Exp 26
Queue
Queue Using Linked Lists
Aim

Write a program for queue operations using linked lists: Enqueue, Dequeue, Display, Is Empty, Size, Exit. Output: "Successfully inserted", "Deleted value: X", "Queue is underflow", "Elements: ...", "Queue is empty/not empty", "Queue size: N".

QueueUsingLL.c (Driver)
#include <stdlib.h>
#include <stdio.h>
#include "QueueOperationsLL.c"
int main() {
        int op, x;
        while(1) {
                printf("1.Enqueue 2.Dequeue 3.Display 4.Is Empty 5.Size 6.Exit\n");
                printf("Option: ");
                scanf("%d",&op);
                switch(op) {
                        case 1:
                                  printf("element: ");
                                  scanf("%d",&x);
                                  enqueue(x);
                                  break;
                        case 2:
                                  dequeue();
                                  break;
                        case 3:
                                  display();
                                  break;
                        case 4:
                                  isEmpty();
                                  break;
                        case 5:
                                  size();
                                  break;
                        case 6: exit(0);
                }
        }
}
QueueOperationsLL.c
struct queue {
int data;
struct queue*next;
};
typedef struct queue*Q;
Q front=NULL,rear=NULL;
void enqueue(int element){
        Q temp=NULL;
        temp=(Q)malloc(sizeof(struct queue));
                if(temp==NULL){
                 printf("queue is overflow\n");
                 }
        else{
                 temp->data=element;
                 temp->next=NULL;
                 if(front==NULL){
                         front=temp;
                 }
                 else{
                           rear->next=temp;
                 }
                 rear=temp;
                 printf("Successfully inserted\n");
        }
}
        void dequeue(){
                 Q temp=NULL;
                 if(front==NULL){
                 printf("Queue is underflow\n");
        }
        else{
                 temp=front;
                 if(front==rear){
                         front=rear=NULL;
                 }
                 else{
                         front=front->next;
                 }
                 printf("Deleted value: %d\n",temp->data);
                 free(temp);
        }
        }
void display(){
        if(front==NULL){
                 printf("Queue is empty\n");
        }
          else{
                    Q temp=front;
                    printf("Elements: ");
                    while(temp!=NULL){
                            printf("%d ",temp->data);
                            temp=temp->next;
                    }
                    printf("\n");
          }
}
void size(){
        int count=0;
          if(front==NULL){
                  printf("Queue size: 0\n");
          }
          else{
                    Q temp=front;
                    while(temp!=NULL){
                    temp=temp->next;
                    count=count+1;
                          }
          printf("Queue size: %d\n",count);
          }
}

void isEmpty(){
        if(front==NULL){
                    printf("Queue is empty\n");
          }
          else{
                    printf("Queue is not empty\n");
          }
}
Exp 27
Queue Application
Printer Queue System Simulation
Aim

Develop a C program to simulate a simple printer queue system. Note: Before exiting, all jobs must be done.

PrinterQueue.c
#include <stdio.h>
#include <stdlib.h>

// Define a structure for a print job
struct PrintJob {
    int jobId;
    struct PrintJob* next;
};

// Define a structure for the printer queue
struct PrinterQueue {
    struct PrintJob* front;
     struct PrintJob* rear;
};

// Function to initialize an empty printer queue
void initializeQueue(struct PrinterQueue* queue) {
        queue->front=NULL;
        queue->rear=NULL;
}

// Function to check if the queue is empty
int isQueueEmpty(struct PrinterQueue* queue) {
        return (queue->front==NULL);
}

// Function to enqueue a print job
void enqueue(struct PrinterQueue* queue, int jobId) {
        struct PrintJob*newJob=(struct PrintJob*)malloc(sizeof(struct PrintJob));
        newJob->jobId=jobId;
        newJob->next=NULL;
        if(isQueueEmpty(queue)){
                queue->front=queue->rear=newJob;
        }else{
                 queue->rear->next=newJob;
                queue->rear=newJob;}
        printf("Job %d added\n", jobId);
}

// Function to dequeue a print job
void dequeue(struct PrinterQueue* queue) {
        if(isQueueEmpty(queue)){
                printf("No job to dequeue\n");
                 return;
        }
        struct PrintJob*temp=queue->front;
        queue->front=queue->front->next;
        printf("Job %d removed from queue and sent to the printer\n",temp->jobId);
        free(temp);
        if(queue->front==NULL){
        queue->rear=NULL;
        }
}

int main() {
    struct PrinterQueue printerQueue;
    initializeQueue(&printerQueue);
    int choice, jobId;
    do {
        printf("Printer Queue System\n");
        printf("1. Add a job to queue\n");
        printf("2. Process the next job\n");
        printf("3. Exit\n");
        printf("Choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                printf("Job ID: ");
                scanf("%d", &jobId);
                enqueue(&printerQueue, jobId);
                break;
            case 2:
                dequeue(&printerQueue);
                break;
            case 3:
                printf("Exiting\n");
                break;
            default:
                printf("Invalid choice\n");
        }
    } while (choice != 3);

    // Cleanup: free remaining print jobs in the queue
    while (!isQueueEmpty(&printerQueue)) {
        dequeue(&printerQueue);
    }
        return 0;
}
Exp 28
Circular Queue
Circular Queue Using Arrays (MAX=6)
Aim

Design, Develop and Implement a menu driven Program for Circular QUEUE of Characters with max size MAX=6: Insert, Delete, Overflow/Underflow Demo, Display, Exit.

cQue.c
#include <stdio.h>
#include<stdlib.h>
#include<stdio_ext.h>
#define MAX 6

int cq[MAX];
int front = -1, rear = -1;

void insert(int);
void delete();
void display();

void insert(int item)
{   if(front == (rear+1)%MAX) {
        printf("~~~Circular Queue Overflow~~~\n");       }
    else {
                  if(front==-1)
                          front=rear=0;
                  else
                          rear=(rear+1)%MAX;
                  cq[rear]=item;
    }
}

void delete()
{   char item;
    if(front == -1)
    {   printf("~~~Circular Queue Underflow~~~\n");      }
    else
    {   item = cq[front];
        printf("Deleted element from the queue is: %d\n",item );
        if(front==rear)
                          front=rear=-1;
        else
                          front=(front+1)%MAX;
    }
}

void display ()
{   int i ;
    if(front == -1)
    {   printf("~~~Circular Queue Empty~~~\n");      }
    else
    {   printf("Circular Queue contents are:\n");
                  for(i=front;i!=rear;i=(i+1)%MAX)
                          printf("%d ",cq[i]);
                    printf("%d\n",cq[i]);
        }
}

void main()
{   int ch, item;
    while(1)
        {   printf("~~Main Menu~~");
            printf("\n=> 1. Insertion and Overflow Demo");
            printf("\n=> 2. Deletion and Underflow Demo");
            printf("\n=> 3. Display");
            printf("\n=> 4. Exit");
            printf("\nEnter Your Choice: ");
            scanf("%d", &ch);
            __fpurge(stdin);
            switch(ch)
            {   case 1: printf("Enter the element to be inserted: ");
                        scanf("%d", &item);
                         insert(item);
                         break;
                 case 2: delete();
                         break;
                 case 3: display();
                         break;
                 case 4: exit(0);
                 default: printf("Please enter a valid choice\n");
            }
        }
}
Exp 29
Circular Queue
Circular Queue Using Linked List
Aim

Write a program to implement circular queue using linked lists. Menu: Enqueue, Dequeue, Display, Is empty, Size, Exit.

CQueueLL.c (Driver)
#include <stdlib.h>
#include <stdio.h>
#include "CQueueOperationsLL.c"
int main() {
          int op, x;
          while(1) {
                  printf("1.Enqueue 2.Dequeue 3.Display 4.Is empty 5.Size 6.Exit\n");
                 printf("Enter your option : ");
                 scanf("%d",&op);
                 switch(op) {
                         case 1:
                                    printf("Enter element : ");
                                    scanf("%d",&x);
                                    enqueue(x);
                                    break;
                          case 2:
                                    dequeue();
                                    break;
                          case 3:
                                    display();
                                    break;
                          case 4:
                                    isEmpty();
                                    break;
                          case 5:
                                    size();
                                    break;
                          case 6: exit(0);
                 }
          }
}
CQueueOperationsLL.c
struct queue {
        int data;
        struct queue *next;
};
typedef struct queue *CircularQueue;
CircularQueue front = NULL, rear = NULL;

void dequeue() {
        CircularQueue temp=NULL;
        if(front==NULL){
                printf("Circular queue is underflow.\n");
        }
        else{
                temp=front;
                if(front==rear){
                        front=rear=NULL;
                }
                else{
                        front=front->next;
                        rear->next=front;
                }
                printf("Deleted value = %d\n",temp->data);
                free(temp);
        }
}

void size() {
        int count =0;
        if(front == NULL) {
                printf("Circular queue size : 0\n");
                return;
        }
        CircularQueue temp = front;
        do {
                temp = temp -> next;
                count = count + 1;
        } while(temp != front);
        printf("Circular queue size : %d\n",count);
}

void isEmpty() {
        if(front == NULL ) {
                printf("Circular queue is empty.\n");
        } else {
                printf("Circular queue is not empty.\n");
        }
}

void enqueue(int element) {
        CircularQueue temp=NULL;
          temp=(CircularQueue)malloc(sizeof(struct queue));
          if(temp==NULL){
                  printf("Circular queue is overflow.\n");
          }
          else{
                  temp->data=element;
                  temp->next=NULL;
                  if(front==NULL){
                          front=temp;
                  }
                  else{
                          rear->next=temp;
                  }
                  rear=temp;
                  rear->next=front;
                  printf("Successfully inserted.\n");
          }
}

void display() {
        if(front == NULL) {
                 printf("Circular queue is empty.\n");
          } else {
                  CircularQueue temp = front;
                  printf("Elements in the circular queue : ");
                  do {
                          printf("%d ", temp -> data);
                          temp = temp -> next;
                  } while(temp != front);
                  printf("\n");
          }
}
Exp 30
Stack Application
Convert Infix to Postfix & Evaluate
Aim

Write a C program that uses a stack to convert an infix expression to postfix and then evaluate it. Only single-digit positive integers and +,-,*,/,% operators allowed.

Output: Line 1 – postfix expression; Line 2 – result of evaluation.

EvaluateConverted.c
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define MAX 100
char charstack[100];
int chartop=-1;
int intstack[MAX];
int inttop=-1;
void pushchar(char c){
        if(chartop<MAX-1){
                charstack[++chartop]=c;
        }
}
char popchar(){
        if(chartop>=0){
                return charstack[chartop--];
        }
        return '\0';
}
char peekchar(){
        if(chartop>=0){
                return charstack[chartop];
        }
        return '\0';
}
void pushint(int num){
        if(inttop<MAX-1){
                intstack[++inttop]=num;
        }
}
int popint(){
        if(inttop>=0){
                return intstack[inttop--];
        }
        return 0;
}
int precedence(char op){
        switch(op){
                case '+':
                case '-':
                return 1;
                case '*':
                case '/':
                case '%':
                return 2;
                default:
                return 0;
        }
}
void infixpostfix(char* infix,char* postfix){
        int k=0;
        for(int i=0;infix[i]!='\0';i++){
                if(isdigit(infix[i])){
                           postfix[k++]=infix[i];
                }
                else if(infix[i]=='('){
                        pushchar(infix[i]);}
                else if(infix[i]==')'){
                        while(chartop!=-1&&peekchar()!='('){
                                   postfix[k++]=popchar();
                           }
                           popchar();
                }
                else{
while(chartop!=-1&&precedence(peekchar())>=precedence(infix[i])){
                                postfix[k++]=popchar();
                           }
                           pushchar(infix[i]);
                }
        }
        while(chartop!=-1){
                postfix[k++]=popchar();
        }
        postfix[k]='\0';
}
int evaluatepostfix(char* postfix){
        for(int i=0;postfix[i]!='\0';i++){
                if(isdigit(postfix[i])){
                        pushint(postfix[i]-'0');
                }
                else{
                           int val2=popint();
                           int val1=popint();
                           switch(postfix[i]){
                                   case '+':pushint(val1+val2);
                                  break;
                                  case '-':pushint(val1-val2);
                                  break;
                                  case '*':pushint(val1*val2);
                                  break;
                                  case '/':pushint(val1/val2);
                                  break;
                                  case '%':pushint(val1%val2);
                                  break;
                           }
                }
        }
        return popint();
}
int main(){
            char infix[MAX],postfix[MAX];
            printf("Infix expression: ");
            scanf("%s",infix);
            infixpostfix(infix,postfix);
            printf("Postfix expression: %s\n",postfix);
            int result=evaluatepostfix(postfix);
            printf("Result: %d\n",result);
            return 0;
}
All Test Cases Passed
Test Case 1
Infix expression: 2+3*4 Postfix expression: 234*+ Result: 14
Test Case 2
Infix expression: 8%3+6*(2-1) Postfix expression: 83%621-*+ Result: 8
Exp 31
Stack Application
Check String Symmetry Using Stack
Aim

Implement a C program that uses a stack to determine whether a given string is symmetric (reads same forward and backward). Case-insensitive. Convert all chars to lowercase before checking.

Output: "<string> is symmetric" or "<string> is not symmetric"

StringSymmetry.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAX 100
char stack[MAX];
int top=-1;
// Define a stack structure
struct Stack {
int top;
char items [100];
}
// Function to initialize the stack
void initializeStack(struct Stack*
stack) {
  stack->top = -1;
}
//function to create 
int isSymmetricUsingStack(char* str) {
    struct Stack s;
    initializeStack(&s);
    int len = strlen(str);
    
    // Push elements onto the stack directly
    for (int i = 0; i< len; i++) {
        s.items[++s.top] = str[i];
    }
    
    for (int i = 0; i< len; i++) {
        if (tolower(str[i]) != tolower(s.items[s.top--])) {
            return 0; 
        }
    }
    return 1;
}

int main(){
        char str[MAX];
        char lowerstr[MAX];
        printf("String: ");
        scanf("%s",str);
        tolowercase(str,lowerstr);
        if(issymmetric(str)){
                printf("%s is symmetric\n",str);
        }else{
                printf("%s is not symmetric\n",str);
        }
}
All Test Cases Passed
Test Case 1
String: Emualator Emualator is not symmetric
Test Case 2
String: Madam Madam is symmetric
Exp 32
Queue Application
Check String Symmetry Using Queue
Aim

Implement a C program that uses a queue to determine whether a given string is symmetric. Case-insensitive. Convert to lowercase before checking.

Output: "<string> is symmetric" or "<string> is not symmetric"

StringSymmetryUsingQueue.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>

// Define the structure for queue node
struct Node {
     char data;
     struct Node* next;
};

// Define the structure for the queue
struct Queue {
    struct Node *front, *rear;
};
struct Node* newNode(char data){
        struct Node*temp=(struct Node*)malloc(sizeof(struct Node));
        temp->data=data;
        return temp;
}
struct Queue* createQueue(){
        struct Queue* q=(struct Queue*)malloc(sizeof(struct Queue));
        q->front=q->rear=NULL;
        return q;
}
void enqueue(struct Queue*q,char data){
        struct Node* temp=newNode(data);
        if(q->rear==NULL){
                q->front=q->rear=temp;
                return;
        }
        q->rear->next=temp;
        q->rear=temp;
}
char dequeue(struct Queue* q){
        if(q->front==NULL){
                printf("Queue is empty\n");
                return -1;
        }
        struct Node*temp=q->front;
        char data=temp->data;
        q->front=q->front->next;
        free(temp);
        if(q->front==NULL){
                q->rear=NULL;
        }
          return data;
}
bool isSymmetric(char *str){
        struct Queue* q=createQueue();
          int i=0;
          while(str[i]){
                  enqueue(q,tolower(str[i]));
                  i++;
          }
          while(q->front!=NULL){
                     char frontchar=dequeue(q);
                     if(frontchar!=tolower(str[--i])){
                             return false;
                      }
                 }
return true;
}

int main() {
      char str[100];
      printf("String: ");
      scanf("%s", str);
      if (isSymmetric(str)) {
          printf("%s is symmetric\n", str);
      } else {
          printf("%s is not symmetric\n", str);
      }
      return 0;
}
All Test Cases Passed
Test Case 1
String: abcdcba abcdcba is symmetric
Test Case 2
String: Alpha Alpha is not symmetric
Unit 06

Binary Search Trees & Hashing

Exp 33
Binary Search Tree
BST Insert & Inorder / Preorder / Postorder Traversal
Aim

Write a program to create a BST and perform: Insert a node, In-order traversal, Pre-order traversal, Post-order traversal.

"Successfully inserted." or "Element already exists in BST."

BinarySearchTree.c (Driver)
#include<stdio.h>
#include<stdlib.h>
#include "InsertAndTraversals.c"

void main() {
        int x, op;
        BSTNODE root = NULL;
        while(1) {
                printf("1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit\n");
                printf("Enter your option : ");
                scanf("%d", &op);
                switch(op) {
                        case 1: printf("Enter an element to be inserted : ");
                                       scanf("%d", &x);
                                       root = insertNodeInBST(root,x);
                                       break;
                        case 2:
                                       if(root == NULL) {
                                                  printf("Binary Search Tree is empty.\n");
                                       }
                                       else {
                                                  printf("Elements of the BST (in-order traversal): ");
                                                  inorderInBST(root);
                                                  printf("\n");
                                                  }
                                       break;
                        case 3:
                                       if(root == NULL) {
                                               printf("Binary Search Tree is empty.\n");
                                       }
                                       else {
                                                  printf("Elements of the BST (pre-order traversal): ");
                                                  preorderInBST(root);
                                                  printf("\n");
                                                  }
                                       break;
                        case 4:
                                       if(root == NULL) {
                                                  printf("Binary Search Tree is empty.\n");
                                  }
                                  else {
                                             printf("Elements of the BST (post-order traversal): ");
                                             postorderInBST(root);
                                             printf("\n");
                                             }
                                  break;
                        case 5:
                                  exit(0);
                }
        }
}
InsertAndTraversals.c
struct node {
        int data;
        struct node *left, *right;
};

typedef struct node *BSTNODE;

BSTNODE newNodeInBST(int item) {
        BSTNODE temp = (BSTNODE)malloc(sizeof(struct node));
        temp->data = item;
        temp->left = temp->right = NULL;
        return temp;
}

BSTNODE insertNodeInBST(BSTNODE node, int ele) {
        if(node==NULL){
                printf("Successfully inserted.\n");
                return newNodeInBST(ele);
        }
        if(ele<node->data)
                node->left=insertNodeInBST(node->left,ele);
        else if(ele>node->data)
                node->right=insertNodeInBST(node->right,ele);
        else
                printf("Element already exists in BST.\n");
        return node;
}
void inorderInBST(BSTNODE root) {
        if(root!=NULL){
                inorderInBST(root->left);
                printf("%d ",root->data);
                inorderInBST(root->right);
        }
}
void preorderInBST(BSTNODE root) {
if(root!=NULL){
        printf("%d ",root->data);
        preorderInBST(root->left);
        preorderInBST(root->right);
}
}
void postorderInBST(BSTNODE root) {
     if(root!=NULL){
                 postorderInBST(root->left);
                postorderInBST(root->right);
                printf("%d ",root->data);
          }
}
Exp 34
Binary Search Tree
BST — Insert & Delete Node
Aim

Write a program to create a BST and perform Insert and Delete operations. Show inorder and preorder traversal before and after deletion.

BinarySearchTree.c (Insert & Delete)
#include <stdio.h>
#include <stdlib.h>
struct node {
  int key;
     struct node *left, *right;
};

// Creation
struct node *newNode(int item) {
  struct node *temp = (struct node *)malloc(sizeof(struct node));
     temp->key = item;
     temp->left = temp->right = NULL;
     return temp;
}

// Inorder Traversal using recursion
void inorder(struct node *root) {
  if (root != NULL) {
         // Traverse left
         inorder(root->left);
         // Traverse root
         printf("%d ", root->key);
         // Traverse right
         inorder(root->right);
     }
}

void preorder(struct node *root) {
     if (root != NULL) {
       // Traverse left
        printf("%d ", root->key);
         preorder(root->left);
         // Traverse right
         preorder(root->right);
     }
}
// Find the inorder successor
struct node *minValueNode(struct node *node) {
  struct node *current = node;
     // Find the leftmost leaf
     while (current && current->left != NULL)
       current = current->left;
     return current;
}

// Insert a node in BST
struct node *insert(struct node *node, int key) {
if(node==NULL)return newNode(key);
         if(key<node->key)node->left=insert(node->left,key);
         else
                 node->right=insert(node->right,key);
         return node;
}

// Deleting a node
struct node *deleteNode(struct node *root, int key) {
         if(root==NULL)return root;
         if(key<root->key)
                 root->left=deleteNode(root->left,key);
         else if(key>root->key)
                 root->right=deleteNode(root->right,key);
         else{
                 if(root->left==NULL){
                         struct node *temp=root->right;
                          free(root);
                          return temp;
                 }
                 else if(root->right==NULL){
                         struct node*temp=root->left;
                         free(root);
                     return temp;
                 }
                 struct node*temp=minValueNode(root->right);
                 root->key=temp->key;
                 root->right=deleteNode(root->right,temp->key);
         }
         return root;
}

// Driver code
int main() {
  struct node *root = NULL;
    int n,data;
    printf("Enter how many nodes you want to insert in BST :");
    scanf("%d",&n);
    for( int i =0 ; i < n ; i++){
        printf("Enter the value: ");
        scanf("%d", &data);
        root = insert(root, data);
    }

    printf("Inorder traversal(Always gives ascending order): ");
    inorder(root);
    printf("\nPreorder traversal: ");
    preorder(root);
    printf("\nEnter the data to delete: ");
    scanf("%d",&data);

    printf("After deleting %d\n",data);

    root = deleteNode(root, data);
    printf("Inorder traversal: ");
    inorder(root);
    printf("\nPreorder traversal: ");
    preorder(root);
}
Exp 35
Hashing
Linear Probing Collision Resolution
Aim

Write a C program to implement Linear Probing (Hash Table size=10). Menu: Insert, Delete, Search, Print, Exit. Output: "Successfully inserted.", "Successfully deleted.", "Element found.", "Element not found.", "[index]=>value" format for print.

HashingMain2.c (Driver)
#include <stdio.h>
#include <stdlib.h>
#include "HashingLinearProbing.c"
int main() {
        int x, op, i = 0;
        for (i = 0; i < SIZE; i++)
                HashTable[i] = -1;
        while (1) {
                printf("1.Insert 2.Delete 3.Search 4.Print 5.Exit\n");
                printf("Enter your option : ");
                 scanf("%d", &op);
                 switch (op) {
                         case 1: printf("Enter an element to be inserted : ");
                                        scanf("%d", &x);
                                        insert(x);
                                        break;
                         case 2:
                                        printf("Enter an element to be deleted : ");
                                        scanf("%d", &x);
                                        deleteElement(x);
                                        break;
                         case 3:
                                        printf("Enter an element to be searched : ");
                                        scanf("%d", &x);
                                        search(x);
                                        break;
                         case 4:
                                        print();
                                         break;
                         case 5: exit(0);
                 }
        }
}
HashingLinearProbing.c
#define SIZE 10
int HashTable[SIZE];
int hash(int x) {
        return x % SIZE;
}
void insert(int x) {
        int index=hash(x);
        while(HashTable[index]!=-1){
                index=(index+1)%SIZE;
        }
        HashTable[index]=x;
        printf("Successfully inserted.\n");
}
void deleteElement(int x) {
        int index=hash(x);
        while(HashTable[index]!=-1){
                if(HashTable[index]==x){
                        HashTable[index]=-1;
                           printf("Successfully deleted.\n");
                           return;
                }
                index=(index+1)%SIZE;
        }
        printf("Element not found. So cannot delete the element.\n");
}
void search(int x) {
        int index=hash(x);
        while(HashTable[index]!=-1){
                if(HashTable[index]==x){
                        printf("Element found.\n");
                        return;
                }
                index=(index+1)%SIZE;
        }
        printf("Element not found.\n");
}
void print() {
        for(int i=0;i<SIZE;i++){
                if(HashTable[i]!=-1){
                           printf("[%d]=>%d ",i,HashTable[i]);
                }
        }
        printf("\n");
}
Exp 36
Hashing
Separate Chaining Collision Resolution
Aim

Write a C program to implement Separate Chaining (Hash Table size=10). Menu: Insert, Delete, Search, Print, Exit. Print format: "[index]=> v1 v2 ..." per chain.

HashingMain4.c (Driver)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include "HashingSeperateChaining.c"
int main() {
        int x, op, i=0;
        for(i=0;i<SIZE;i++)
                HashTable[i]=NULL;
        while(1) {
                printf("1.Insert 2.Delete 3.Search 4.Print 5.Exit\n");
                 printf("Enter your option : ");
                 scanf("%d", &op);
                 switch(op) {
                         case 1: printf("Enter an element to be inserted : ");
                                        scanf("%d", &x);
                                        insert(x);
                                        break;
                         case 2:
                                        printf("Enter an element to be deleted : ");
                                        scanf("%d", &x);
                                        deleteElement(x);
                                        break;
                         case 3:
                                        printf("Enter an element to be searched : ");
                                        scanf("%d", &x);
                                        search(x);
                                        break;
                         case 4:
                                         print();
                                         break;
                         case 5: exit(0);
                 }
        }
}
HashingSeperateChaining.c
#define SIZE 10
struct node {
        int data;
        struct node * next;
};
struct node * HashTable[SIZE];

int hash(int x) {
        return x % SIZE;
}

struct node * newNode(int x) {
        struct node * temp = (struct node *) malloc(sizeof(struct node *));
        temp->data = x;
        temp->next = NULL;
        return temp;
}
void insert(int x) {
        int index=hash(x);
        struct node*newE1=newNode(x);
        if(HashTable[index]==NULL){
                  HashTable[index]=newE1;
        }else{
                  struct node*temp=HashTable[index];
                  newE1->next=temp;
                  HashTable[index]=newE1;
        }
}
void deleteElement(int x) {
        int index=hash(x);
        struct node*current=HashTable[index];
        struct node*prev=NULL;
        while(current!=NULL&&current->data!=x){
                prev=current;
                current=current->next;
        }
        if(current==NULL){
                  printf("Element not found. So cannot delete.\n");
                  return;
        }
        if(prev==NULL){
                HashTable[index]=current->next;
        }else{
                  prev->next=current->next;
          }
          free(current);
          printf("Successfully deleted.\n");
}
void search(int x) {
        int index=hash(x);
        struct node*temp=HashTable[index];
          while(temp!=NULL){
                  if(temp->data==x){
                          printf("Element found.\n");
                           return;
                  }
                  temp=temp->next;
          }
          printf("Element not found.\n");
}
void print() {
        for(int i=0;i<SIZE;i++){
                  struct node*temp=HashTable[i];
                  if(temp!=NULL){
                           printf("[%d]=> ",i);
                           while(temp!=NULL){
                                   printf("%d ",temp->data);
                                     temp=temp->next;
                           }
                  }
          }
          printf("\n");
}
Exp 37
Hashing Application
Simple Cache Using Hashing (Linear Probing)
Aim

Implement a C program to create a simple cache using hashing. Handles key-value pairs, collisions via linear probing. Menu: Insert key-value pair, Retrieve value for key, Exit.

Output: "Value for key X: value", "Key X not found in the cache", "Cache is full. Unable to insert."

Cache.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define CACHE_SIZE 10
typedef struct {
int key;
char value[256];
} CacheItem;
CacheItem cache[CACHE_SIZE];
void initialize_cache() {
        for(int i=0;i<CACHE_SIZE;i++){
                cache[i].key=-1;
                strcpy(cache[i].value, "");
        }
}
int hash(int key) {
        return key%CACHE_SIZE;
}
void insert(int key,char *value){
        int index=hash(key);
        int original_index=index;
        int found=0;
        do{
                if(cache[index].key==-1||cache[index].key==key){
                        cache[index].key=key;
                        strcpy(cache[index].value,value);
                        found=1;
                        break;
                }
                index=(index+1)%CACHE_SIZE;
        }while(index!=original_index);
        if(!found){
                printf("Cache is full. Unable to insert.\n");
        }
}
void retrieve(int key){
        int index=hash(key);
        int original_index=index;
        int found=0;
        do{
                if(cache[index].key==key){
                        printf("Value for key %d: %s\n",key,cache[index].value);
                        found=1;
                        break;
                }
                if(cache[index].key==-1){
                        break;
                }
                index=(index+1)%CACHE_SIZE;
        }while(index!=original_index);
        if(!found){
                printf("Key %d not found in the cache\n",key);
        }
}
void display_menu() {
        printf("Cache Menu:\n");
        printf("1. Insert a key-value pair\n");
        printf("2. Retrieve value for a key\n");
        printf("3. Exit\n");
        printf("Choice: ");
}
int main(){
        initialize_cache();
        int choice;
        while(1){
                display_menu();
                scanf("%d",&choice);
                        switch(choice){
                        case 1: {
                                int key;
                                char value[256];
                                printf("Key: ");
                                scanf("%d",&key);
                                printf("Value: ");
                                scanf("%s",value);
                                insert(key,value);
                                break;
                        }
                        case 2: {
                                int key;
                                printf("Key for retrieval: ");
                                scanf("%d",&key);
                                retrieve(key);
                                break;
                        }
                        case 3:
                        printf("Exiting\n");
                        return 0;
                        default:
                        printf("Invalid choice\n");
                        break;
                        }
        }
        return 0;
}
All Test Cases Passed
Test Case 1 Excerpt
Key for retrieval: 10 → Key 10 not found in the cache Insert key=10 value=010, key=20 value=020 Key for retrieval: 10 → Value for key 10: 010 Key for retrieval: 20 → Value for key 20: 020