Showing posts with label Data Structure. Show all posts
Showing posts with label Data Structure. Show all posts

C program to find and replace a string in a sentence

C Program for finding a pattern in a sentence and replace it with another string.
//main string: Manoj Kumar Sahu
//string to be found and replaced: uma
//new string to be replaced with uma: UMA
//resultant string: Manoj KUMAr Sahu
#include<stdio.h>
#include<string.h>
#include<malloc.h>
char* fr(char* str, char* old, char* new)
{
int count=0, i=0;
char* ret;
int lenold = strlen(old);
int lennew = strlen(new);
for(i=0;str[i]!='\0';i++)
{
if(strstr(&str[i],old)==&str[i])
{
count=count+1;
lenold=lenold-1;
}
else{}
}
ret=(char*)malloc(i+count*(lennew-lenold));
i=0;
while(*str)
{
    //if(strstr(&str[i],old)=&str[i])//l value required
    if(strstr(str,old)==str)
    {
    //copy
    strcpy(&ret[i],new);
    i=i+lennew;
    str=str+lenold;
    }
    else
    {
    ret[i]=*str;
    i++;   
    str++;
    }
}
return ret;
}
int main()
{
char str[]="manoj kumar sahu";
char old[]="uma";
char new[]="UMA";
char *result=fr(str,old,new);
printf("resltanc string=%s\n",result);
return 0;
}

Remove consecutive repeated characters from a string.

//C program to remove consecutive repeated characters from string.
//C program to remove consecutive repeated elements from an array.

#include <stdio.h>
#include<string.h>
int main()
{

int i,j,len,len1;
char str[100];
printf("Enter a string with repeated adjacent characters:");
gets(str);
    len=strlen(str);

    //assign 0 to len1 - length of removed characters
    len1=0;

    //Removing consecutive repeated characters from string
    for(i=0; i<(len-len1);)
    {
        if(str[i]==str[i+1])
        {
            //shift all characters
            for(j=i;j<(len-len1);j++)
                str[j]=str[j+1];
            len1++;
        }
        else
        {
            i++;
        }
    }

    printf("String after removing duplicate adjacent elements : %s\n",str);

    return 0;
}
/*
Enter a string with repeated adjacent characters:abbcccdefabc
String after removing duplicate adjacent elements : abcdefabc
*/
//Removing consecutive members in an array
#include<iostream>
using namespace std;

class Base
{

};
void print(int* p)
{
while(*p)
cout<<*p++<<" ";
cout<<endl;
};
int main()
{
cout<<""<<endl;
int arr[]={1,2,2,3,3,2,4,5,5,55,555,5};

print(arr);
int size=sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;)
{
if(arr[j]==arr[j+1])
{
for(int k=j;k<size;k++)
{
arr[k]=arr[k+1];
}
//shift
size--;
}
else
{
//check next
j++;
}
}
}
print(arr);
return 0;
}
/*
1 2 2 3 3 2 4 5 5 55 555 5
1 2 3 2 4 5 55 555 5
*/

C program to find only unique elements of array

//C++ Program to find only unique elements in array of integers.
using namespace std;
#include <stdio.h>
#include <string.h>
//#include <stdlib.h>
int main() {
   int arr[20], i, j, k, size;

   printf("\nEnter the size of the array : ");
   scanf("%d", &size);

   printf("\nEnter the Numbers in array : ");
   for (i = 0; i < size; i++)
      scanf("%d", &arr[i]);

   printf("\nArray with Unique elements is  : ");
   for (i = 0; i < size; i++) {
      for (j = i + 1; j < size;) {
         if (arr[j] == arr[i]) {
            for (k = j; k < size; k++) {
               arr[k] = arr[k + 1];
            }
            size--;
         } else
         {
            j++;
         }
      }
   }

   for (i = 0; i < size; i++) {
      printf("%d ", arr[i]);
   }
    printf("\n");
   return (0);
}
/*
Enter the size of the array : 8
Enter the Numbers in array :
1
2
2
3
4
2
3
1
Array with Unique elements is  : 1 2 3 4
*/
//C Program to remove all duplicate elements from an array
#include<iostream>
using namespace std;

class Base
{

};
void print(int* p)
{
while(*p)
cout<<*p++<<" ";
cout<<endl;
};
int main()
{
cout<<""<<endl;
int arr[]={1,2,2,3,3,2,4,5,5,55,555,5};

print(arr);
int size=sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<size;k++)
{
arr[k]=arr[k+1];
}
//shift
size--;
}
else
{
//check next
j++;
}
}
}
print(arr);
return 0;
}
/*
1 2 2 3 3 2 4 5 5 55 555 5
1 2 3 4 5 55 555
*/

C program to find frequency of each character in a string

//C/Cpp/C++ program to find frequency of each characters in a string
//C/Cpp/C++ program to find non repeating characters in a string
//C/Cpp/C++ program to find repeating characters in a string
//C/Cpp/C++ program to output a1b2c3d4 when input is "abbcccdddd"
/*Idea is to keep count of each characters
'a'=count[0] occurs how many times 0,1,2.3..
'b'=count[1] occurs how many times 0,1,2,3..
.
.
'z'=count[25] occurs how many times 0,1,2,3....
*/
#include<iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
int main()
{
char a='a';
cout<<"a-97="<<a-97<<endl;//0
cout<<"'a'-97="<<'a'-97<<endl;//0

cout<<"manin()\n";
char arr[]="abbccc";
int count[26];
int i;
for(i=0;i<26;i++)
count[i]=0;

i=0;
//while(arr[i]!='\0')
for(i=0;i<strlen(arr);i++)
{
printf("arr[i]=%c arr[i]-97=%d count[arr[i]-97]]=%d\n",arr[i],arr[i]-97,count[arr[i]-97]);
if(arr[i]>='a' && arr[i]<='z')
    count[arr[i]-97]=count[arr[i]-97]+1;//count[arr[i]-97]++;
if(arr[i]>='A' && arr[i]<='Z')
    count[arr[i]-65]=count[arr[i]-65]+1;//count[arr[i]-65]++;
//i++;
}

printf("\nPrinting frequency of each character:\n");
for(i=0;i<25;i++)
{
if(count[i]>0)//characters which occurs atleast once
printf(" %c%d",i+97,count[i]);//a1b2c3
}
printf("\nPrinting repeated character:\n");
for(i=0;i<25;i++)
{
if(count[i]>1)//characters which occurs atleast 2
printf(" %c%d",i+97,count[i]);//a1b2c3
}
printf("\nPrinting character which are unique or none repeating characters:\n");
for(i=0;i<25;i++)
{
if(count[i]==1)//characters which occurs only once or uniquely
printf(" %c%d",i+97,count[i]);//a1b2c3
}


printf("\n");
return 0;
}
/*
a-97=0
'a'-97=0
manin()
arr[i]=a arr[i]-97=0 count[arr[i]-97]]=0
arr[i]=b arr[i]-97=1 count[arr[i]-97]]=0
arr[i]=b arr[i]-97=1 count[arr[i]-97]]=1
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=0
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=1
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=2

Printing frequency of each character:
a1 b2 c3
Printing repeated character:
b2 c3
Printing character which are unique or none repeating characters:
a1
http://www.codeforwin.in/2015/04/c-program-to-calculate-the-frequency-of-each-character-in-a-line.html
*/

C program to convert Decimal to binary, binary to decimal, reverse a number, pallindrom check

Decimal to Binary
//C program to convert decimal to binary
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a decimal number:";//13
cin>>num;
int n,r,i=1;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%2;//13%2=1 //6%2=0 //3%2=1 //1%2=1//
n=n/2;//13/2=6 //6/2=3 //3/2=1 //1/2=0
s=s+r*i;//0+1*1=1 //1+0*10=1 //1+1*100=101 //101+1*1000=1101
i=i*10;//1*10=10//10*10=100 //100*10=1000 //10000
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"Decimal number "<<num<<" in binary is: "<<s<<endl;//1101

return 0;
}
/*
Enter a decimal number:13
r=1 n=6 s=1 i=10
r=0 n=3 s=1 i=100
r=1 n=1 s=101 i=1000
r=1 n=0 s=1101 i=10000
Decimal number 13in binary is: 1101
*/
//Binary to Decimal
#include<iostream>
using namespace std;
#include<math.h>

int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a binary number:";//1101=13
cin>>num;
int n,r,i=0;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%10;//
n=n/10;//
s=s+r*pow(2,i);//
++i;
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"binary number "<<num<<" in Decimal is: "<<s<<endl;//1101

return 0;
}
/*
manin()
Enter a binary number:1101
r=1 n=110 s=1 i=1
r=0 n=11 s=1 i=2
r=1 n=1 s=5 i=3
r=1 n=0 s=13 i=4
binary number 1101 in Decimal is: 13
*/
//Sum of digits of a numbers
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1//1/10=0
sum=sum+r;//4//4+3//4+3+2//4+3+2+1=10
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//10
return 0;
}
//Reverse Number
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//4321
return 0;
}
//Pallindrom number
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
if(num==sum)
{
cout<<"Its a pallindrom "<<num<<" is equal to "<<sum<<endl;//4321
}
else
{
cout<<"Not a pallindrom.\n";
}
return 0;
}
//Reversing String
#include<iostream>
using namespace std;
#include<string.h>
void strRev(char *arr);

int main()
{
cout<<"manin()\n";
char arr[]="Hello";
///*
int result;
char *end;
char *start;
end=arr;
start=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<=l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
//*/
cout<<"reversed string is:"<<arr<<endl;
cout<<"\nAgain reversing using function:\n";
strRev(arr);
cout<<"arr is now again: "<<arr<<endl;
//cout<<"Reverse string is: "<<strRev(arr)<<endl;
return 0;
}
void strRev(char *arr)
{
char *start=arr;
char *end=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
}
/*
manin()
reversed string is:olleH
Again reversing using function:
arr is now again: Hello
*/

C program to merge two sorted arrays. Array Union

//C/C++/C Plus Plus program to merge two sorted arrays
//C/C++/C Plus Plus program to find union of two sorted arrays
#include<iostream>
using namespace std;
#include<stdio.h>

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5,7,8,9};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
{
printf("%d",arr1[i]);
i++;
}
else if(arr2[j]<arr1[i])
{
printf("%d",arr2[j]);
j++;
}
else //arr[i]==arr[j]
{
printf("%d",arr2[j]);
i++;
j++;
}
}
while(i<n1)
printf("%d",arr1[i++]);
while(j<n2)
printf("%d",arr2[j++]);

cout<<endl;
}
//output
//12345789

C program to find common numbers in two sorted arrays. Array intersection

//C/C++/C Plus Plus program to find common numbers in two sorted arrays
//C/C++/C Plus Plus program to find intersection of two sorted arrays
//C/C++/C Plus Plus program to find common elements of two sorted arrays
#include<iostream>
using namespace std;

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
i++;
else if(arr2[j]<arr1[i])
j++;
else //arr[i]==arr[j]
{
cout<<"common elements are:"<<arr2[j]<<endl;
i++;
j++;
}

}
}

C Program for sorting an array using Bubble Sort and Insertion Sort

#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int arr[20],n,i,j,t;
cout<<"Enter the number of elements in array:"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0;i<n;i++)
cin>>arr[i];

cout<<"Entered the elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";

/*
cout<<"Bubble sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
cout<<n-i-1<<" "<<j<<" "<<j+1<<" "<<endl;
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
*/
//OR
/*
Selection sort: By first scanning the entire list before locating the exact pair of numbers to swap, only two writes to memory are performed by Selection Sort for each O(n) scan,whereas
Bubble Sort does writes on each and every comparison. So, Bubble Sort does O(n^2) writes. while selection sort does O(n) writes to mwmory.
*/
cout<<"\nSelection sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)//mind n-1
{
for(j=i+1;j<n;j++) //mind n
{
if(arr[i]>arr[j])
{
cout<<n<<" "<<i<<" "<<j<<" "<<endl;
t=arr[j];
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}


cout<<"Sorted array elements are:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";

cout<<endl;
return 0;
}
/*
//Selection Sort:
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
4 1 2
4 2 3
4 3 4
4 4 5
3 2 3
3 3 4
3 4 5
2 3 4
2 4 5
1 4 5
Sorted array elements are:
1 2 3 4 5

//Bubble sort

manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
5 0 1
5 0 2
5 0 3
5 0 4
5 1 2
5 1 3
5 1 4
5 2 3
5 2 4
5 3 4
Sorted array elements are:
1 2 3 4 5
*/
/*
In Bubble sort , at every iteration you find a largest number and push it to bottom (Bubble out larger number)
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.

Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better
For both insertion and bubble sort worst case is O(n^2)
*/

Find and remove loop in linked list code in cpp linux

//Remove Loop in a linked list1.
//Find the loop and pass the loop node to removeLoop function.
//assign pointer ptr1=start.
//start infinite loop.
//assign pointer ptr2=loopnode.
//in loop traverse till ptr2->next!=loopnode && ptr2->next!=ptr1
//loop is found when ptr2->next=ptr1 ; break the loop
//else increment ptr1//most important
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
//Inserting at start
void insert(struct node** ref,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*ref);
*ref=newnode;//mind it
}
//displaying
void display(struct node *ref)
{
struct node *ptr=ref;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
//Detecting Loop
void loopDetect()
{
struct node* slow=start;
struct node* fast=start;
while(start->next !=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
printf("LoopDetected\n");
removeLoop(slow);
break;//else infinite time LoopDetected gets printed
}
}
}
void removeLoop(struct node *loopnode)
{
printf("\nRemoveLoop Called.\n");
struct node *ptr1;
struct node *ptr2;
ptr1=start;
while(1)
{
ptr2=loopnode;
while(ptr2->next != loopnode && ptr2->next!=ptr1)
{
ptr2=ptr2->next;
}
if(ptr2->next==ptr1)//mind the next
break;
else
ptr1=ptr1->next;
}
ptr2->next=NULL;
}
int main()
{
insert(&start,10);
insert(&start,20);
insert(&start,30);
insert(&start,40);
insert(&start,50);
display(start);
//create a loop
start->next->next->next->next=start->next;
//display(start);//infinite loop means loop created.
loopDetect();
display(start);//No infinite loop means No loop now.

return 0;
}
/*
50 40 30 20 10
LoopDetected
50 40 30 20
*/
--------------------------
//Remove Loop in a linked list1.

C Linux code to insert in middle of Linked list

//Inserting After given node of Single Linked List
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
        int data;
        struct node* next;
};
struct node *start=NULL;
void push(struct node** ref,int d)
{
        struct node *newnode=(struct node *)malloc(sizeof(struct node));
        newnode->data=d;
        newnode->next=(*ref);
        (*ref)=newnode;
}
void display(struct node *start)
{
        struct node *ptr=start;
        while(ptr)
        {
                printf("%d\t",ptr->data);
                ptr=ptr->next;
        }
        printf("\n");
}
struct node* insertAfterNode(struct node *start,int d, int afternode)
{
int i;
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=d;
struct node* current=start;
while(current!=NULL)
{
if(current->data==afternode)
{
newnode->next=current->next;
current->next=newnode;
//return start;
}
current=current->next;
}
}
int main()

How to merge two sorted arrays in C Language

/*Merging two sorted arrays:
input: two sorted arrays a and b and 1 output array c
1.compare a and b, if a[i]< c[k] put that in c[k] else put b[j]in c[k]
2.when any of array is empty put the remaining elements of other array's
elements in C as it is.*/
#include<stdio.h>
#include<stdlib.h>
void mergeSorted(int a[], int b[], int c[], int asize, int bsize, int
csize);

int main()
{
int i;
int a[]={5,10,15,20,25};
int b[]={2,4,6,8,10};
int c[10];
mergeSorted(a,b,c,5,5,10);
printf("Merged Array is:\n");
for(i=0;i<10;i++)
{
printf("%d ",c[i]);/* 2 4 5 6 8 10 10 15 20 25 */
}

printf("\n\n");
return 0;
}

void mergeSorted(int *a, int *b, int *c, int asize, int bsize, int csize)
{
printf("\nin mergeSorted:\n");
int ai=0,bi=0,ci=0,i;
//csize=asize+bsize;
/*compare a[ai]<b[bi] till any of the array ends.*/
while((ai<asize) && (bi<bsize))
{
if(a[ai]<=b[bi])
{
c[ci]=a[ai];
ci++;
ai++;
}
else
{
c[ci]=b[bi];
ci++;
bi++;
}
}
if(ai>=asize)
for(i=ci;i<csize;i++,bi++)
c[i]=b[bi];

else if(bi>=bsize)
for(i=ci;i<csize;i++,ai++)
c[i]=a[ai];


}

How to detect/find Loop in a Linked List in C Code

/*C Linux code for detecting Loop/cycle in as a linked list.
Take two pointers advance one by one and the other by 2 nodes.
If these pointers meet then loop is present else not.*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
void insert(struct node **,int d);
void display(struct node *);
int findLoop(struct node *);

int main()
{
int result;
insert(&head,10);
insert(&head,20);
insert(&head,30);
insert(&head,40);
insert(&head,50);
insert(&head,60);
display(head);
printf("\nCreate some loop.\n");
head->next->next->next->next->next=head;
result=findLoop(head);
if(result==1)
{

printf("\nYes,Loop Present in Linked List.\n ");
}
else
{

printf("\nNo,Loop Present in Linked List.\n ");
}
printf("\n");
return 0;
}
void insert(struct node **head,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*head);
(*head)=newnode;
}
void display(struct node *head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
}
int findLoop(struct node *head)
{
struct node *slow=head;
struct node *fast=head;
while((fast->next!=NULL) && (fast->next->next!=NULL))
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
//printf("\nYes,Loop Present in Linked List.\n ");
return 1;
}
}
return 0;
}
/*
When run with loop outpt is:

50 40 30 20 10
Create some loop.
Yes,Loop Present in Linked List.

When run commenting loop outpt is:
50 40 30 20 10
No,Loop Present in Linked List.
*/

How to find middle node of a Linked List in C Linux Code

/*C Linux code for finding the middle of a linked list.
Method-1- count the node and the count/2 th element is the middle
element of the Linked List.
Methode 2:- take two pointers advance one by one and the other by 2.
When fast pointer reaches end of the loop the slow reaches to middle
node of the LinkedList.*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
void insert(struct node **,int d);
void display(struct node *);
void findMiddle(struct node *);

int main()
{
insert(&head,10);
insert(&head,20);
insert(&head,30);
insert(&head,40);
insert(&head,50);
display(head);
findMiddle(head);

printf("\n");
return 0;
}
void insert(struct node **head,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*head);
(*head)=newnode;
}
void display(struct node *head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
}
void findMiddle(struct node *head)
{
struct node *slow=head;
struct node *fast=head;
// if(head)
// {
while((fast->next!=NULL) && (fast->next->next!=NULL))
{
slow=slow->next;
fast=fast->next->next;
}
// }
printf("\nThe middle node is:%d ",slow->data);
}
/*

60 50 40 30 20 10
The middle node is:40

*/

Queue using Linked List in C

/*code for implementing queue operations using linked list*/
#include<stdio.h>
#include<stdlib.h>
struct node

{
int data;

struct node* link;

};

struct node *front=NULL;

struct node *rear=NULL;



void insert(int);

void display();

void del();



void insert(int d)

{

struct node *newnode=(struct node *)malloc(sizeof(struct node));

newnode->data=d;

newnode->link=NULL;



if(front==NULL)

{

front=rear=newnode;

}

else

{

rear->link=newnode;

rear=newnode;

}

}

void display()

{

if(front==NULL){printf("\nQueue is empty.\n");}

else

{

struct node *ptr;

ptr=front;

while(ptr)

{

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

ptr=ptr->link;

}

}

printf("\n");

}

void del()

{

struct node* temp;

temp=front;

if(front==NULL){printf("\nQueue is Empty.\n");}

else

{

struct node* temp;

temp=front;

front=front->link;

//rear->link=front;

free(temp);

}

}



int main()

{

insert(10);

insert(20);

insert(100);

insert(40);

insert(300);

display();

del();

display();

return 0;

}

/*

10 20 100 40 300

20 100 40 300

*/

Queue Operations Using Array in C

/* Queue using Array */
#include<stdio.h>
#define MAXSIZE 4

int cq[MAXSIZE];

int front=-1, rear=-1;

void insert(int item)

{

printf("Insert called:\n");

if( ( (front==0)&&(rear==MAXSIZE-1)%MAXSIZE ) ||
front==(rear+1)%MAXSIZE )

{

printf("Queue is full.\n");

}

else

{

if(front==-1)

front=rear=0;

else

rear=(rear+1)%MAXSIZE;



cq[rear]=item;

printf("\nfront =%d rear=%d\n",front,rear);



}



}





void display()

{

printf("\n");

int i;

for(i=0;i<MAXSIZE;i++)

{

printf("%d ",cq[i]);

//printf("%d %d ",front,rear);

}

printf("\n");

}





void deletee()

{

if(front==-1)

{

printf("Queue is empty\n");

}

else

{

int temp;

temp=cq[front];

cq[front]=0;

if(front==rear)//only 1 elt was there

front=rear=-1;//delete the single so q is empty

else

front=(front+1)%MAXSIZE;//if more than 1 elt then delete
frm front



printf("deleted elt is: %d\n",temp);

printf("\n front = %d rear = %d\n",front,rear);

}

}



int main()

{

insert(10);

insert(20);

insert(30);

insert(40);

display();



insert(111);//Q is full so make same place by deleting fronts

display();



deletee();

display();

insert(100);

display();







return 0;

}

/*



Insert called:



front =0 rear=0

Insert called:



front =0 rear=1

Insert called:



front =0 rear=2

Insert called:



front =0 rear=3



10 20 30 40

Insert called:

Queue is full.



10 20 30 40

deleted elt is: 10



front = 1 rear = 3



0 20 30 40

Insert called:



front =1 rear=0



100 20 30 40



*/

Stack implementation using Linked List through C Linux Code

/* stack using linked list */

#include<stdio.h>

#include<stdlib.h>

struct node

{

int data;

struct node *next;

};



void push(int);

void display();

int pop();



struct node *top=NULL;



int main()

{

push(10);

push(20);

push(30);

display();

pop();

display();

pop();

display();

pop();

display();



return 0;

}



void push(int d)

{

struct node *newnode;

newnode=(struct node *)malloc(sizeof(struct node));

if(newnode==NULL) printf("\nout of memory\n");

else

{

newnode->data=d;

newnode->next=top;

top=newnode;

}

}



int pop()

{

struct node *temp;

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

if(top==NULL)

{

printf("Under flow\n");

return -1;

}

else

{

temp=top;

//int info;

//info=top->data;

top=top->next;

if(temp!=NULL)

free(temp);

//return(info);

}

}



void display()

{

printf("\ndisplay callled:\n");

struct node *current;

if(top==NULL)

printf("\nstack empty\n");

else

{

current=top;

while(current)

{

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

current=current->next;

}

}



printf("\n");

}

/*



display callled:

30 20 10



display callled:

20 10



display callled:

10



display callled:



stack empty



*/

Stack implementation using array in C

/*stack implementation using array
push pop operation
*/
#include<stdio.h>
void push(int item);
int pop();
void display();
int stack[10];
int top=-1;
int main()
{
push(10);
push(20);
push(30);
push(40);
push(50);
display();
printf("\n");
pop();
pop();
display();
return 0;
}
void push(int item)
{
if(top==9)
{
printf("Stack is full.\n");
return;
}
top++;
stack[top]=item;
}
int pop()
{
printf("\npop called.\n");
if(top==-1)
{
printf("stack is empty\n");
return -1;
}
int item;
item=stack[top];
top--;
return item;
}
void display()
{
printf("\ndisplay called.\n");
int i;
for(i=top;i>=0;i--)
{
printf("%d ",stack[i]);
}
}
/*
display called.
50 40 30 20 10
pop called.
pop called.
display called.
30 20 10
*/
//stack to reverse a string
//Stack appalication to reverse a sentence
//read array elts. push into stack,pop,display
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 20
char stack[SIZE];
int top=-1;
int i;
        void push(char c);
        int pop();
int main()
{
        char arr[]="World is not enough";
        printf("org string is: %s\n",arr);
        for(i=0;i<SIZE-1;i++)
        {
                push(arr[i]);

        }
        for(i=0;i<SIZE-1;i++)
        {
                arr[i]=pop();

        }
        printf("rev string is: %s\n",arr);

return 0;
}
        void push(char c)
        {
                if(top==SIZE-1)
                printf("overflow");
                else
                stack[++top]=c;
        }
        int pop()
        {
                if(top==-1)
                printf("underflow\n");
              else
                return stack[top--];
        }
/*
org string is: World is not enough
rev string is: hguone ton si dlroW
*/

Deleting from a sorted array through C Linux Code

/*Code for deleting from a sorted array: */
#include<stdio.h>
#include<stdlib.h>
int deleteSorted(int *a,int *size,int item);
int main()
{
int n,i;
int a[]={2,4,6,8,10};
printf("Original sorted array is:\n");

for(i=0;i<5;i++)
{

printf("%d ",a[i]);
}

printf("\nEnter element to be deleted:\n");

scanf("%d",&n);

int size=5;

deleteSorted(a,&size,n);

printf("\nAfter delete sorted array is:\n");

for(i=0;i<size;i++)

{

printf("%d ",a[i]);

}

printf("\n");

return 0;

}


int deleteSorted(int *a,int *size,int item)

{

printf("Inside deleteSorted:\n");

int i=0,j;

/*compare item with a[i] till i<size when matches come out*/

for(i=0;i<*size;i++)

{

if(a[i]==item)

{

break;

}

else if(i==*size-1)

{

printf("Not found \n");

return -1;

}

}

for(j=i;j<*size;j++)

{

a[j]=a[j+1];

}

(*size)--;

}

/*shift the elts to left*/

/*

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

2

Inside deleteSorted:



After delete sorted array is:

4 6 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

4

Inside deleteSorted:


After delete sorted array is:

2 6 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

5

Inside deleteSorted:

Not found


After delete sorted array is:

2 4 6 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

6

Inside deleteSorted:


After delete sorted array is:

2 4 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

55

Inside deleteSorted:

Not found

After delete sorted array is:

2 4 6 8 10

*/

/*

Code for deleting from a sorted array:

*/

#include<stdio.h>

#include<stdlib.h>

int deleteSorted(int *a,int *size,int item);

int main()

{

int n,i;

int a[]={2,4,6,8,10};

printf("Original sorted array is:\n");

for(i=0;i<5;i++)

{

printf("%d ",a[i]);

}

printf("\nEnter element to be deleted:\n");

scanf("%d",&n);

int size=5;

deleteSorted(a,&size,n);

printf("\nAfter delete sorted array is:\n");

for(i=0;i<size;i++)

{

printf("%d ",a[i]);

}

printf("\n");

return 0;

}

int deleteSorted(int *a,int *size,int item)

{

printf("Inside deleteSorted:\n");

int i=0,j;

/*compare item with a[i] till i<size when matches come out*/

while((a[i]!=item)&&(i<*size))

{

i++;

}

if(i==*size)

{

printf("Could not find the elet.\n");

return (-1);

}

/*shift the elts to left*/

for(j=i;j<*size-1;j++)

a[j]=a[j+1];

(*size)--;

}

/*

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

2

Inside deleteSorted:

After delete sorted array is:

4 6 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

4

Inside deleteSorted:

After delete sorted array is:

2 6 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to be deleted:

10

Inside deleteSorted:

After delete sorted array is:

2 4 6 8

*/

Inserting in a sorted array through C Linux Code

/*Code for inserting in a sorted array*/

#include<stdio.h>

int insertSorted(int *a,int *size,int item);

int main()

{

int n,i;

int a[]={2,4,6,8,10};

printf("Original sorted array is:\n");

for(i=0;i<5;i++)

{

printf("%d ",a[i]);

}

printf("\nEnter element to insert:\n");

scanf("%d",&n);

int size=5;

insertSorted(a,&size,n);

printf("\nAfter Inserted sorted array is:\n");

for(i=0;i<=5;i++)

{

printf("%d ",a[i]);

}

printf("\n");

return 0;

}

int insertSorted(int *a,int *size,int item)

{

int i,j;//i is position

if(*size<0) {printf("Enter a positive array size.\n"); return;}

/*Determine the location to insert.*/

if(item<a[0])

{

i=0;

}

else

{

for(i=1;i<*size;i++)

{

if(( item<=a[i]) && (item>=a[i-1]))

{

break;//come out of the loop when right position

}

}

}

/*Shift the elemets after the position to insrt to right*/

for(j=*size;j>=i;j--)

a[j]=a[j-1];

/*Insert the lement at rigt postion*/

a[i]=item;

(*size)++;

}

/*

Original sorted array is:

2 4 6 8 10

Enter element to insert:

11

After Inserted sorted array is:

2 4 6 8 10 11

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to insert:

1

After Inserted sorted array is:

1 2 4 6 8 10

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to insert:

33

After Inserted sorted array is:

2 4 6 8 10 33

[user02@localhost ds]$ ./a.out

Original sorted array is:

2 4 6 8 10

Enter element to insert:

3

After Inserted sorted array is:

2 3 4 6 8 10

*/

Compress Array by Extracting Unique elements of an array in C on Linux Platform

   C Linux Code to extract the unique numbers only.
   0. assign the first elt to result array
   1.Traverse through the array
   2.compare first to next and if not equal the copy to the resultant array
   if input array is
   int arr[]={1,1,2,2,2,3,4,5,5};
   then output array should be
   1 2 3 4 5

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

int* zeroshift(int *, int);
int main()
{
    int size,i,j;
    int arr[]={1,1,2,2,2,3,4,5,5};
    size=sizeof(arr)/sizeof(int);
    int* ptr=zeroshift(arr,size);
    printf("After after elemenating the repeated elements, array is:\n");
    for(i=0;i<size;i++)
        printf("%d ",ptr[i]);
    printf("\n");
    return 0;
}

int* zeroshift(int *arr,int size)
{
    int i;
    int count=0;
    int *result=(int *)malloc(size*sizeof(int));
    result[count++]=arr[0];
    for(i=0;i<size-1;i++)/* 1.Traverse through the array*/
    {
        if(arr[i]!=arr[i+1])
        {
            result[count]=arr[i+1];/*2.copy the non equal elts to new array say result and increment the count*/
            count++;
        }

    }
    return result;
}
/*
   1 2 3 4 5
 */