Merge branch 'master' into master

This commit is contained in:
Ashwek Swamy 2019-10-30 14:24:19 +05:30 committed by GitHub
commit c385a79149
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
210 changed files with 7340 additions and 1708 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.swp
*.out

View File

@ -1,34 +0,0 @@
#include<conio.h>
#include<stdio.h>
#include<math.h>
float f(float x)
{
return 1.0+x*x*x;
}
void main()
{
int i,n;
float a,b,h,x,s2,s3,sum,integral;
printf("enter the lower limit of the integration");
sacnf("%f",&a);
printf("enter the upper limit of the integration");
sacnf("%f",&b);
printf("enter the number of intervals");
sacnf("%d",&n);
h=(b-a)/n;
sum=f(a)+f(b);
s2=s3=0.0;
for(i=1;i<n;i+=3)
{
x=a+i*h;
s3=s3+f(x)+f(x+h);
}
for(i=3;i<n;i+=3)
{
x=a+i*h;
s2=s2+f(x);
}
intgeral=(h/3.0)*(sum+2*s2+4*s3);
printf("\nvalue of the integral =%9.4f\n",integral);
getch();
}

View File

@ -1,116 +0,0 @@
# Statistic-library for C
This repository contains a statistic library for the C programming language which prepare useful functions for dealing with average, standard deviation etc. The library is platform-independent. So you can use this library with any C-compiler.
### Usage
You needed to put in the files ```statistic.h``` and ```statistic.c``` in your project directory. After that you include the header file ```statistic.h```
in your project. Then you can use the functions of this library. You will find the files ```statistic.h``` and ```statistic.c``` in the directory **src**.
### Overview about the functions
The first int-argument represents the size of the sample (double-array).
```c
/*
Computes the average of a given sample.
The sample is a set of double values.
The average-function gets a variable number of arguments.
The first argument must be the number of arguments!
The averageArray-function instead gets a double-array of values and a int-number that
represents the size of the double-array.
*/
double average_Array(int,const double[]);
double average(int,...);
```
```c
/*
Computes the standard deviation (n-1)
*/
double standard_deviation(int,...);
double standard_deviation_array(int, const double[]);
/*
Computes the standard deviation (n)
*/
double standard_deviation_N(int,...);
double standard_deviation_N_array(int, const double[]);
```
```c
/*
variance: computes the variance (n-1)
variance_N: computes the variance (n)
*/
double variance(int, const double[]);
double variance_N(int, const double[]);
```
```c
/*
gets the max (min) element of the sample
*/
double max(int, const double[]);
double min(int , const double[]);
```
```c
/*
computes the median of the sample
*/
double median(int, const double[]);
```
```c
/*
adds up all values of the sample.
*/
double sum(int,const double[]);
```
```c
/*
computes the range of the sample.
*/
double range(int, const double[]);
```
```c
/*
gets the frequency of the last argument (double) of that sample.
*/
double frequency_of(int, const double[], double);
```
```c
/*
quartile_I: computes the first quartile.
quartile_III: computes the third quartile.
The second quartile is the median!
*/
double quartile_I(int, const double[]);
double quartile_III(int, const double[]);
```
```c
/*
computes the quartile distance
*/
double quartile_distance(int, const double[]);
```
### Running the tests
You navigate in the directory of this repository and type in the console:
```bash
gcc -o myTests test/test.c src/statistic.c -lcunit -lm && ./myTests
```
#### Dependencies for tests
* CUnit
* gcc

View File

@ -1,400 +0,0 @@
/*
author: Christian Bender
This file contains the implementation part of the statistic-library.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include "statistic.h"
double average(int n, ...)
{
va_list valist;
double sum = 0;
int i;
/* initializes valist for num number of arguments */
va_start(valist, n);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
sum += va_arg(valist, double);
}
/* cleans memory reserved for valist */
va_end(valist);
return sum / n;
}
double average_Array(int n, const double values[])
{
int i;
double sum = 0;
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
sum += values[i];
}
return sum / n;
}
double standard_deviation(int n, ...)
{
va_list valist;
double var = 0;
double avg = 0;
double value = 0;
double values[n];
int i;
/* initializes valist for num number of arguments */
va_start(valist, n);
for (i = 0; i < n; i++)
{
values[i] = va_arg(valist, double);
}
va_end(valist);
va_start(valist, n);
/* fetches the average */
avg = average_Array(n, values);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
value = va_arg(valist, double);
var += (value - avg) * (value - avg);
}
var /= (double)(n - 1);
/* cleans memory reserved for valist */
va_end(valist);
return sqrt(var);
}
double standard_deviation_array(int n, const double values[])
{
double var = 0;
double avg = 0;
int i;
/* fetches the average */
avg = average_Array(n, values);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
var += (values[i] - avg) * (values[i] - avg);
}
var /= (double)(n - 1);
return sqrt(var);
}
double standard_deviation_N(int n, ...)
{
va_list valist;
double var = 0;
double avg = 0;
double value = 0;
double values[n];
int i;
/* initializes valist for num number of arguments */
va_start(valist, n);
for (i = 0; i < n; i++)
{
values[i] = va_arg(valist, double);
}
va_end(valist);
va_start(valist, n);
/* fetches the average */
avg = average_Array(n, values);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
value = va_arg(valist, double);
var += (value - avg) * (value - avg);
}
var /= (double)n;
/* cleans memory reserved for valist */
va_end(valist);
return sqrt(var);
}
double standard_deviation_N_array(int n, const double values[])
{
double var = 0;
double avg = 0;
int i;
/* fetches the average */
avg = average_Array(n, values);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
var += (values[i] - avg) * (values[i] - avg);
}
var /= (double)n;
return sqrt(var);
}
double variance(int n, const double values[])
{
double var = 0;
double avg = 0;
int i;
/* fetches the average */
avg = average_Array(n, values);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
var += (values[i] - avg) * (values[i] - avg);
}
var /= (double)(n - 1);
return var;
}
double variance_N(int n, const double values[])
{
double var = 0;
double avg = 0;
int i;
/* fetches the average */
avg = average_Array(n, values);
/* adds up all double values of the sample. */
for (i = 0; i < n; i++)
{
var += (values[i] - avg) * (values[i] - avg);
}
var /= (double)n;
return var;
}
double max(int n, const double values[])
{
double max = values[0];
int i;
/* iterates over all elements in 'values' */
for (i = 1; i < n; i++)
{
if (values[i] > max)
{
max = values[i];
}
}
return max;
}
double min(int n, const double values[])
{
double min = values[0];
int i;
/* iterates over all elements in 'values' */
for (i = 1; i < n; i++)
{
if (values[i] < min)
{
min = values[i];
}
}
return min;
}
/*
private helper-function for comparing two double values
*/
int cmp(const void *a, const void *b)
{
return (*(double *)a - *(double *)b);
}
double median(int n, const double values[])
{
double tmp[n];
int i;
/* clones the array 'values' to array 'tmp' */
for (i = 0; i < n; i++)
{
tmp[i] = values[i];
}
/* sorts the array 'tmp' with quicksort from stdlib.h */
qsort(tmp, n, sizeof(double), cmp);
if (n % 2 != 0) /* n is odd */
{
/* integer division */
return tmp[n / 2];
}
else
{ /* n is even */
/* uses the average(...) function, above. */
return average(2, tmp[n / 2], tmp[(n / 2) - 1]);
}
}
double sum(int n, const double values[])
{
double sum = 0;
int i;
/* actual adding procedure */
for (i = 0; i < n; i++)
{
sum += values[i];
}
return sum;
}
double range(int n, const double values[])
{
return max(n, values) - min(n, values);
}
double frequency_of(int n, const double values[], double val)
{
int i;
double counter = 0;
/* counts the number of occurs */
for (i = 0; i < n; i++)
{
if (values[i] == val)
{
counter++;
}
}
return counter / n;
}
double quartile_I(int n, const double values[])
{
double sum = 0;
double freq = 0;
int i;
int d = 1;
double tmp[n];
for (i = 0; i < n; i++)
{
tmp[i] = values[i];
}
/* sorts the array 'tmp' with quicksort from stdlib.h */
qsort(tmp, n, sizeof(double), cmp);
double lastVal = tmp[0];
freq = frequency_of(n, values, lastVal);
sum += freq;
for (i = 1; i < n; i++)
{
if (tmp[i] != lastVal)
{
freq = frequency_of(n, values, tmp[i]);
sum += freq;
lastVal = tmp[i];
if (sum >= 0.25)
{
if (n % 2 != 0)
{
return values[i];
}
else
{
return average(2, values[i], values[i + 1]);
}
}
}
}
}
double quartile_III(int n, const double values[])
{
double sum = 0;
double freq = 0;
int i;
double tmp[n];
for (i = 0; i < n; i++)
{
tmp[i] = values[i];
}
/* sorts the array 'tmp' with quicksort from stdlib.h */
qsort(tmp, n, sizeof(double), cmp);
double lastVal = tmp[0];
freq = frequency_of(n, values, lastVal);
sum += freq;
for (i = 1; i < n; i++)
{
if (tmp[i] != lastVal)
{
freq = frequency_of(n, values, tmp[i]);
sum += freq;
lastVal = tmp[i];
if (sum >= 0.75)
{
if (n % 2 != 0)
{
return values[i];
}
else
{
return average(2, values[i], values[i + 1]);
}
}
}
}
}
double quartile_distance(int n, const double values[])
{
return quartile_III(n, values) - quartile_I(n, values);
}

View File

@ -1,79 +0,0 @@
/*
author: Christian Bender
This file contains the public interface for the statistic-library.
*/
#ifndef __STATISTIC__H
#define __STATISTIC__H
/*
Computes the average of a given sample.
The sample is a set of double values.
The average-function gets a variable number of arguments. The first argument
must be the number of arguments!
The averageArray-function instead gets a double-array of values and a int-number that
represents the size of the double-array.
*/
double average_Array(int, const double[]);
double average(int, ...);
/*
computes the standard deviation (n-1)
*/
double standard_deviation(int, ...);
double standard_deviation_array(int, const double[]);
/*
computes the standard deviation (n)
*/
double standard_deviation_N(int, ...);
double standard_deviation_N_array(int, const double[]);
/*
variance: computes the variance (n-1)
variance_N: computes the variance (n)
*/
double variance(int, const double[]);
double variance_N(int, const double[]);
/*
gets the max (min) element of the sample
*/
double max(int, const double[]);
double min(int, const double[]);
/*
computes the median of the sample
*/
double median(int, const double[]);
/*
adds up all values of the sample.
*/
double sum(int, const double[]);
/*
computes the range of the sample.
*/
double range(int, const double[]);
/*
gets the frequency of the last argument (double) of that sample.
*/
double frequency_of(int, const double[], double);
/*
quartile_I: computes the first quartile.
quartile_III: computes the third quartile.
The second quartile is the median!
*/
double quartile_I(int, const double[]);
double quartile_III(int, const double[]);
/*
computes the quartile distance
*/
double quartile_distance(int, const double[]);
#endif

View File

@ -1,190 +0,0 @@
/*
author: Christian Bender
This file contains a CUnit test suit for the statistic-library
*/
#include <stdio.h>
#include <CUnit/CUnit.h>
#include "CUnit/Basic.h"
#include "../src/statistic.h"
/* test for function average(...) */
void test_average(void)
{
CU_ASSERT_DOUBLE_EQUAL(average(3,1.0,2.5,3.5),2.333,0.01);
}
/* test for function averageArray(...) */
void test_average_Array(void)
{
double values[] = {1.0, 2.5, 3.5};
CU_ASSERT_DOUBLE_EQUAL(average_Array(3, values), 2.333, 0.01);
}
/* test for function standard_deviation(...) */
void test_standard_deviation(void)
{
CU_ASSERT_DOUBLE_EQUAL(standard_deviation(4, 15.0, 70.0, 25.0, 50.0), 24.8328, 0.01);
}
/* test for function standard_deviation_array() */
void test_standard_deviation_array(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(standard_deviation_array(4, values), 24.8328, 0.01);
}
/* test for function standard_deviation_N(...) */
void test_standard_deviation_N(void)
{
CU_ASSERT_DOUBLE_EQUAL(standard_deviation_N(4, 15.0, 70.0, 25.0, 50.0), 21.5058, 0.01);
}
/* test for function standard_deviation_N_array() */
void test_standard_deviation_N_array(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(standard_deviation_N_array(4, values), 21.5058, 0.01);
}
/* test for the function variance(...) */
void test_variance(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(variance(4, values), 616.6667, 0.01);
}
/* test for the function variance(...) */
void test_variance_N(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(variance_N(4, values), 462.5, 0.01);
}
/* test for the max(...) function */
void test_max(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(max(4, values), 70.0, 0.01);
}
/* test for the min(...) function */
void test_min(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(min(4, values), 15.0, 0.01);
}
/* test for the median(...)-function */
void test_median(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(median(4, values), 37.5, 0.01);
}
/* test for the sum(...)-function */
void test_sum(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(sum(4, values), 160, 0.01);
}
/* test for the range(...)-function */
void test_range(void)
{
double values[] = {15.0, 70.0, 25.0, 50.0};
CU_ASSERT_DOUBLE_EQUAL(range(4, values), 55, 0.01);
}
/* test of frequency_of(...)-function */
void test_frequency_of(void)
{
double values[] = {1.0,7.0,2.5,2.5,6.0};
CU_ASSERT_DOUBLE_EQUAL(frequency_of(5, values,2.5), 0.4, 0.01);
CU_ASSERT_DOUBLE_EQUAL(frequency_of(5, values,6.0), 0.2, 0.01);
}
/* test of quartile_I(...) and quartile_III(...)-function */
void test_quartile(void)
{
double values[] = {3.0,4.0,5.0,7.0,7.0,7.0,8.0,9.0,11.0,13.0,13.0,13.0,15.0,16.0};
double sample[] = {1600.0,2300.0,2300.0,2400.0,2900.0,3200,3500,4500,4600,5200,6500,12000};
CU_ASSERT_DOUBLE_EQUAL(quartile_I(14, values), 7.0, 0.01);
CU_ASSERT_DOUBLE_EQUAL(quartile_III(14, values), 13.0, 0.01);
CU_ASSERT_DOUBLE_EQUAL(quartile_III(12, sample), 4900.0, 0.01);
}
/* test for quartile_distance(...)-function */
void test_quartile_distance(void)
{
double values[] = {3.0,4.0,5.0,7.0,7.0,7.0,8.0,9.0,11.0,13.0,13.0,13.0,15.0,16.0};
CU_ASSERT_DOUBLE_EQUAL(quartile_distance(14, values), 6.0, 0.01);
}
/*
init suite
*/
int init_suite1(void)
{
return 0;
}
/*
clean suite
*/
int clean_suite1(void)
{
return 0;
}
/* test runner */
int main(void)
{
CU_pSuite pSuite = NULL;
/* initializes CUnit */
if (CUE_SUCCESS != CU_initialize_registry())
return CU_get_error();
/* adds the suit "Test for statistic" to the registry */
pSuite = CU_add_suite("Test for statistic", init_suite1, clean_suite1);
if (NULL == pSuite)
{
CU_cleanup_registry();
return CU_get_error();
}
/* registers the individual tests to the test-suite */
if ((NULL == CU_add_test(pSuite, "test of average()", test_average))
|| (NULL == CU_add_test(pSuite, "test of average_Array()", test_average_Array))
|| (NULL == CU_add_test(pSuite, "test of standard_deviation()", test_standard_deviation))
|| (NULL == CU_add_test(pSuite, "test of standard_deviation_array()", test_standard_deviation_array))
|| (NULL == CU_add_test(pSuite, "test of standard_deviation_N_array()", test_standard_deviation_N_array))
|| (NULL == CU_add_test(pSuite, "test of standard_deviation_N()", test_standard_deviation_N))
|| (NULL == CU_add_test(pSuite, "test of variance()", test_variance))
|| (NULL == CU_add_test(pSuite, "test of variance_N()", test_variance_N))
|| (NULL == CU_add_test(pSuite, "test of max()", test_max))
|| (NULL == CU_add_test(pSuite, "test of min()", test_min))
|| (NULL == CU_add_test(pSuite, "test of median()", test_median))
|| (NULL == CU_add_test(pSuite, "test of sum()", test_sum))
|| (NULL == CU_add_test(pSuite, "test of range()", test_range))
|| (NULL == CU_add_test(pSuite, "test of frequency_of()", test_frequency_of))
|| (NULL == CU_add_test(pSuite, "test of quartile_I() and quartile_III()", test_quartile))
|| (NULL == CU_add_test(pSuite, "test of quartile_distance()", test_quartile_distance)))
{
CU_cleanup_registry();
return CU_get_error();
}
/* runs tests */
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
CU_cleanup_registry();
return CU_get_error();
}

View File

@ -1,66 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#define MAXBITS 100
int main()
{
// input of the user
int inputNumber;
// for the remainder
int re;
// contains the bits 0/1
int bits[MAXBITS];
// for the loops
int j;
int i=0;
printf("\t\tConverter decimal --> binary\n\n");
// reads a decimal number from the user.
printf("\nenter a positive integer number: ");
scanf("%d",&inputNumber);
// make sure the input number is a positive integer.
if (inputNumber < 0)
{
printf("only positive integers >= 0\n");
return 1;
}
// actual processing
while(inputNumber>0)
{
// computes the remainder by modulo 2
re = inputNumber % 2;
// computes the quotient of division by 2
inputNumber = inputNumber / 2;
bits[i] = re;
i++;
}
printf("\n the number in binary is: ");
// iterates backwards over all bits
for(j=i-1; j>=0; j--)
{
printf("%d",bits[j]);
}
// for the case the input number is 0
if (i == 0)
{
printf("0");
}
return 0;
}

View File

@ -1,89 +0,0 @@
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define size 100
struct node
{
char data;
struct node* link;
};
int c=0; // c used as counter to check if stack is empty or not
struct node * head; //declaring head pointer globally assigned to NULL
void push(char x) //function for pushing
{
struct node *p,*temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
if(head==NULL) //will be execute only one time i.e, 1st time push is called
{
head=temp;
p=head;
p->link=NULL;
c++;
}
else
{
temp->link=p;
p=temp;
head=p;
c++;
}
}
char pop(void) //function for pop
{
char x;
struct node*p=head;
x=p->data;
head=p->link;
free(p);
c--;
return x;
}
int isBalanced(char *s) {
int i=0;char x;
while(s[i]!='\0') //loop for covering entire string of brackets
{
if(s[i]=='{'||s[i]=='('||s[i]=='[') //if opening bracket then push
push(s[i]);
else
{
if(c<=0) //i.e, stack is empty as only opening brackets are added to stack
return 0;
x=pop();
if( x=='{'&&s[i]!='}')
return 0;
if(x=='['&&s[i]!=']')
return 0;
if(x=='('&&s[i]!=')')
return 0 ;
}i++;
}
if(c==0) //at end if stack is empy which means whole process has been performed correctly so retuen 1
return 1;
else
return 0;
}
int main() {
int t;
scanf("%d",&t);
for(int a0 = 0; a0 < t; a0++){
char s[size];
int result;
scanf("%s",s);
result = isBalanced(s);
if(result==1)
printf("\nYES");
else
printf("\nNO");
}
return 0;
}

View File

@ -1,98 +0,0 @@
//program for stack using array
#include<stdio.h>
void push();
void pop();
void peep();
void update();
int main()
{
int n,a[100],top=0;
//function for pushing the element
void push()
{
printf("\nenter the value to insert");
scanf("%d",&n);
top=top+1;
a[top]=n;
}
//function for poping the element out
void pop()
{
if(top==0)
{
printf("\nstack is empty");
}
else
{
int item;
item=a[top];
top=top-1;
printf("\npoped item is %d ",item);
}
}
//function for peeping the element from top of the stack
void peep()
{
int i;
printf("\nenter the element position to view from top");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nunderflow condition");
}
else
{
int x;
x=a[top-i+1];
printf("\nthe %dth element from top is %d",i,x);
}
}
//function to update the element of stack
void update()
{
int i,n;
printf("\nenter the position to update");
scanf("%d",&i);
printf("\nenter the item to insert");
scanf("%d",&n);
if(top-i+1<0)
{
printf("\nunderflow condition");
}
else
{
a[top-i+1]=n;
}
}
int x;
while(1)
{
printf("\n1.push");
printf("\n2.pop");
printf("\n3.peep");
printf("\n4.update");
printf("\nenter your choice");
scanf("%d",&x);
switch(x)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
update();
break;
default:
printf("\ninvalid choice");
}
}
return(0);
}

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,19 +0,0 @@
/*
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
*/
#include <stdio.h>
int main() {
int n = 0;
int sum = 0;
scanf("%d", &n);
for (int a = 0; a < n; a++) {
if ((a % 3 == 0) || (a % 5 == 0)) {
sum += a;
}
}
printf("%d\n", sum);
}

View File

@ -1,4 +1,9 @@
# C
C
========
## LeetCode Algorithm
- [Solution](https://github.com/TheAlgorithms/C/tree/master/leetcode) for [LeetCode](https://leetcode.com/problemset/all/)
## Computer Oriented Statistical Methods
- Gauss_Elimination
@ -12,45 +17,58 @@
## Conversions
- binary_to_decimal
- decimal _to_binary
- decimal_to_binary
- decimal_to_hexa
- decimal_to_octal
- to_decimal
- hexa_to_octal
## Data Structures
- stack
- queue
- dictionary
linked_list
- linked_list
- singly_link_list_deletion
- stack_using_linkedlists
binary_trees
- binary_trees
- create_node
- recursive_traversals
trie
- trie
- trie
## Searching
- Linear_Search
- Binary_Search
- Other_Binary_Search
- Jump_Search
- Fibonacci_Search
- Interpolation_Search
- Modified_Binary_Search
## Sorting
- binary_insertion_sort
- BinaryInsertionSort
- BubbleSort
- BucketSort
- BogoSort
- comb_sort
- CountingSort
- gnome_sort
- PartitionSort
- ShellSort
- RadixSort
- InsertionSort
- mergesort
- MergeSort
- OtherBubbleSort
- QuickSort
- SelectionSort
- shaker_sort
- ShakerSort
- HeapSort
- StoogeSort
- RadixSort
## Hashing
- sdbm
- djb2
@ -59,18 +77,29 @@
## Misc
- ArmstrongNumber
- Binning
- Factorial
- Fibonacci
- Greatest Common Divisor
- isArmstrong
- LongestSubSequence
- palindrome
- prime factorization
- QUARTILE
- rselect
- strongNumber
- TowerOfHanoi
- Greatest Common Divisor
- Sudoku Solver
- Sudoku Solver
- TowerOfHanoi
## Project Euler
- Problem 1
- Problem 2
- Problem 3
- Problem 4
- Problem 5
- Problem 6
- Problem 7
## exercism
@ -81,3 +110,9 @@ In this directory you will find (in the right order):
* word-count
* rna-transcription
## Simple Client Server Implementation
This directory contains
* client.c
* server.c
First execute server.c in a terminal and then client.c in a different terminal. Enables communication between two terminals.

View File

@ -1,35 +0,0 @@
#include<stdio.h>
int interpolationSearch(int arr[], int n, int x)
{
int q=NULL;
while(q<n)
{
if(arr[q]==x)
return q;
q++;
}
return -1;
}
int main()
{
// Array of items on which search will
// be conducted.
int x;
int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23,
24, 33, 35, 42, 47};
int n = sizeof(arr)/sizeof(arr[0]); //To get length of an array
printf("Enter the no, to be searched");
scanf("%d",&x); // Element to be searched
int index = interpolationSearch(arr, n, x);
// If element was found
if (index != -1)
printf("Element found at position %d", index+1);
else
printf("Element not found.");
return 0;
}

View File

@ -0,0 +1,66 @@
// Write CPP code here
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}

View File

@ -0,0 +1,96 @@
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(sockfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}

View File

@ -1,40 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
int main(){
int* ARRAY=NULL;
int ContinueFilling=1; //This is to know if we should continue filling our array
int ARRAY_LENGTH=0,isSorted=0,i,TEMPORARY_ELEMENT;
//This code part is for filling our array
while(ContinueFilling){
printf("Enter the value number %d \n",ARRAY_LENGTH+1);
ARRAY=(int *)realloc(ARRAY,sizeof(int)*(ARRAY_LENGTH));
scanf("%d",&ARRAY[ARRAY_LENGTH]);
ARRAY_LENGTH+=1;
printf("would you enter an other value (1:Continue/0:Sort the actual array)?\n");
scanf("%d",&ContinueFilling);
}
//Then we sort it using Bubble Sort..
while(!isSorted){ //While our array's not sorted
isSorted=1; //we suppose that it's sorted
for(i=0;i<ARRAY_LENGTH-1;i++){ //then for each element of the array
if(ARRAY[i]>ARRAY[i+1]){ // if the two elements aren't sorted
isSorted=0; //it means that the array is not sorted
TEMPORARY_ELEMENT=ARRAY[i]; //and we switch these elements using TEMPORARY_ELEMENT
ARRAY[i]=ARRAY[i+1];
ARRAY[i+1]=TEMPORARY_ELEMENT;
}
}
}
//And we display it
for(i=0;i<ARRAY_LENGTH;i++){
printf("%d, ",ARRAY[i]);
}
return 0;
}

View File

@ -1,62 +0,0 @@
#include <stdio.h>
void heapify(int *unsorted, int index, int heap_size);
void heap_sort(int *unsorted, int n);
int main() {
int n = 0;
int i = 0;
char oper;
int* unsorted;
printf("Enter the size of the array you want\n");
scanf("%d", &n);
unsorted = (int*)malloc(sizeof(int) * n);
while (getchar() != '\n');
printf("Enter numbers separated by a comma:\n");
while (i != n) {
scanf("%d,", (unsorted + i));
i++;
}
heap_sort(unsorted, n);
printf("[");
printf("%d", *(unsorted));
for (int i = 1; i < n; i++) {
printf(", %d", *(unsorted + i));
}
printf("]");
}
void heapify(int *unsorted, int index, int heap_size) {
int temp;
int largest = index;
int left_index = 2 * index;
int right_index = 2 * index + 1;
if (left_index < heap_size && *(unsorted + left_index) > *(unsorted + largest)) {
largest = left_index;
}
if (right_index < heap_size && *(unsorted + right_index) > *(unsorted + largest)) {
largest = right_index;
}
if (largest != index) {
temp = *(unsorted + largest);
*(unsorted + largest) = *(unsorted + index);
*(unsorted + index) = temp;
heapify(unsorted, largest, heap_size);
}
}
void heap_sort(int *unsorted, int n) {
int temp;
for (int i = n / 2 - 1; i > -1; i--) {
heapify(unsorted, i, n);
}
for (int i = n - 1; i > 0; i--) {
temp = *(unsorted);
*(unsorted) = *(unsorted + i);
*(unsorted + i) = temp;
heapify(unsorted, 0, i);
}
}

View File

@ -1,35 +0,0 @@
#include <stdio.h>
#incude <stdlib.h>
#define MAX 20
//i and j act as counters
//arraySort is the array that is to be sorted
//elmtToInsert will be the element that we will be trying to move to its correct index in the current iteration
int main()
{
int i, elmtToInsert , j , arraySort[MAX] = {0};
for(i = 1 ; i < MAX ; i++) //This array is being sorted in the ascending order.
{
elmtToInsert = arraySort[i]; //Pick up the ith indexed element of the array. It will be the elmtToInsert.
j = i - 1 ;
while(j >= 0 && elmtToInsert < arraySort[j]) /*compare it with each (i-1)th, (i-2)th... max 0th element, till the correct
position of the elmtToInsert, where it is finally greater than the element just
before it, is found */
{
// You'll enter the loop if the elmtToInsert is less than the element just before it.
arraySort[j+1] = arraySort[j]; //shift the current element one place forward to create room for insertion of the elmtToInsert
j--;
}
//when we exit the loop, j+1 will be the index of the correct position of the elmtToInsert
arraySort[j+1] = elmtToInsert ; //'insert' the elmtToInsert into its correct position
}
return EXIT_SUCCESS;
}

View File

@ -1,100 +0,0 @@
#include <stdio.h>
/*Displays the array, passed to this method*/
void display(int arr[], int n){
int i;
for(i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
/*Swap function to swap two values*/
void swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
}
/*Partition method which selects a pivot
and places each element which is less than the pivot value to its left
and the elements greater than the pivot value to its right
arr[] --- array to be partitioned
lower --- lower index
upper --- upper index
*/
int partition(int arr[], int lower, int upper){
int i = (lower - 1);
int pivot = arr[upper]; // Selects last element as the pivot value
int j ;
for(j = lower; j < upper ; j++){
if(arr[j] <= pivot){ // if current element is smaller than the pivot
i++; // increment the index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1] , &arr[upper]); // places the last element i.e, the pivot to its correct position
return (i + 1);
}
/*This is where the sorting of the array takes place
arr[] --- Array to be sorted
lower --- Starting index
upper --- Ending index
*/
void quickSort(int arr[], int lower, int upper){
if(upper > lower){
// partitioning index is returned by the partition method , partition element is at its correct poition
int partitionIndex = partition(arr, lower, upper);
// Sorting elements before and after the partition index
quickSort(arr, lower, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, upper);
}
}
int main(){
int n;
printf("Enter size of array:\n");
scanf("%d", &n); // E.g. 8
printf("Enter the elements of the array\n");
int i;
int arr[n];
for(i = 0; i < n; i++){
scanf("%d", &arr[i] );
}
printf("Original array: ");
display(arr, n); // Original array : 10 11 9 8 4 7 3 8
quickSort(arr, 0, n-1);
printf("Sorted array: ");
display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
return 0;
}

View File

@ -1,89 +0,0 @@
//sorting of linked list using selection sort
#include<stdio.h>
struct node
{
int info;
struct node *link;
};
struct node *start=NULL;
//func to create node
struct node *createnode()
{
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
return(p);
}
//program to insert at begining
void insert()
{struct node *t;
t=createnode();
printf("\nenter the value to insert");
scanf("%d",&t->info);
if(start==NULL)
{start=t;
}
else
{strutc node *p;
p=start;
t->link=p;
start=t;
}
//program to sort the linked list using selection sort
void sort()
{
struct node *p,*t;
t=start;
int tmp;
for(t=start;t->link!=NULL;t=t->link)
{
for(p=t->link;p!=NULL;p=p->link)
{
if(t->info>p->info)
tmp=t->info;
t->info=p->info;
p->info=tmp;
}
}
//program to view sorted list
void viewlist()
{
struct node *p;
if(start==NULL)
{
printf("\nlist is empty");
}
else
{
p=start;
while(p!=NULL)
{
printf("%d",p->info);
p=p->link;
}
}
int main()
{
int n;
whhile(1)
{
printf("\n1.insert value at beg");
printf("\n2.sort the list");
printf("\n3.view value");
printf("\nenter your choice");
scanf("%d",&n);
switch(n)
{case 1:
insert();
break;
case 2:
sort();
break;
case 3:
viewlist();
break;
default:
printf("\ninvalid choice");
}
}
return(0);
}

View File

@ -1,62 +0,0 @@
/*
Binary Insertion sort is a variant of Insertion sorting in which proper location to insert the selected element is found using the binary search.
*/
#include<stdio.h>
int binarySearch(int a[], int item, int low, int high)
{
if (high <= low)
return (item > a[low])? (low + 1): low;
int mid = (low + high)/2;
if(item == a[mid])
return mid+1;
if(item > a[mid])
return binarySearch(a, item, mid+1, high);
return binarySearch(a, item, low, mid-1);
}
// Function to sort an array a[] of size 'n'
void insertionSort(int a[], int n)
{
int i, loc, j, k, selected;
for (i = 1; i < n; ++i)
{
j = i - 1;
selected = a[i];
// find location where selected sould be inseretd
loc = binarySearch(a, selected, 0, j);
// Move all elements after location to create space
while (j >= loc)
{
a[j+1] = a[j];
j--;
}
a[j+1] = selected;
}
}
int main()
{
int n;
scanf("%d",&n) ;
int a[n],i;
for(i = 0; i<n; i++)
{
scanf("%d",&a[i]);
}
insertionSort(a, n);
printf("Sorted array: \n");
for (i = 0; i < n; i++)
printf("%d ",a[i]);
return 0;
}

View File

@ -1,48 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shellSort(int array[], int value){
int i = value;
int j, k, tmp;
for (i = value / 2; i > 0; i = i / 2){
for (j = i; j < value; j++){
for(k = j - i; k >= 0; k = k - i){
if (array[k+i] >= array[k]){
break;
}
else{
tmp = array[k];
array[k] = array[k+i];
array[k+i] = tmp;
}
}
}
}
}
int main(){
int array[20];
int range = 500;
for(int i = 0; i < 100; i++){
array[i] = rand() % range + 1;
}
int size = sizeof array / sizeof array[0];
clock_t start = clock();
shellSort(array,size);
clock_t end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("Data Sorted\n");
printf("%s\n", "Shell Sort Big O Notation:\n--> Best Case: O(n log(n))\n--> Average Case: depends on gap sequence\n--> Worst Case: O(n)\n");
printf("Time spent sorting: %f\n", time_spent);
return 0;
}

View File

@ -1,34 +0,0 @@
#include<conio.h>
#include<stdio.h>
#include<math.h>
float f(float x)
{
return 1.0+x*x*x;
}
void main()
{
int i,n;
float a,b,h,x,s2,s3,sum,integral;
printf("enter the lower limit of the integration");
sacnf("%f",&a);
printf("enter the upper limit of the integration");
sacnf("%f",&b);
printf("enter the number of intervals");
sacnf("%d",&n);
h=(b-a)/n;
sum=f(a)+f(b);
s2=s3=0.0;
for(i=1;i<n;i+=3)
{
x=a+i*h;
s3=s3+f(x)+f(x+h);
}
for(i=3;i<n;i+=3)
{
x=a+i*h;
s2=s2+f(x);
}
intgral=(h/3.0)*(sum+2*s2+4*s3);
printf("\nvalue of the integral =%9.4f\n",integral);
getch();
}

View File

@ -0,0 +1,41 @@
#include<stdio.h>
#include<math.h>
float f(float x)
{
return 1.0+x*x*x; //This is the expresion of the function to integrate?
}
void main()
{
int i,n;
float a,b,h,x,s2,s3,sum,integral;
printf("enter the lower limit of the integration:");
scanf("%f",&a);
printf("enter the upper limit of the integration:");
scanf("%f",&b);
printf("enter the number of intervals:");
scanf("%d",&n);
h=(b-a)/n;
sum=f(a)+f(b);
s2=s3=0.0;
for(i=1;i<n;i+=3)
{
x=a+i*h;
s3=s3+f(x)+f(x+h);
}
for(i=3;i<n;i+=3)
{
x=a+i*h;
s2=s2+f(x);
}
integral=(h/3.0)*(sum+2*s2+4*s3);
printf("\nValue of the integral = %9.4f\n",integral);
return 0;
}

View File

@ -8,7 +8,7 @@
int main() {
int remainder, number = 0, decimal_number = 0, temp = 1;
printf("Enter any binary number= ");
printf("/n Enter any binary number= ");
scanf("%d", &number);
// Iterate over the number until the end.

View File

@ -0,0 +1,132 @@
/* C program to convert Hexadecimal to Octal number system */
#include <stdio.h>
int main()
{
char hex[17];
long long octal, bin, place;
int i = 0, rem, val;
/* Input hexadecimal number from user */
printf("Enter any hexadecimal number: ");
gets(hex);
octal = 0ll;
bin = 0ll;
place = 0ll;
/* Hexadecimal to binary conversion */
for(i=0; hex[i]!='\0'; i++)
{
bin = bin * place;
switch(hex[i])
{
case '0':
bin += 0;
break;
case '1':
bin += 1;
break;
case '2':
bin += 10;
break;
case '3':
bin += 11;
break;
case '4':
bin += 100;
break;
case '5':
bin += 101;
break;
case '6':
bin += 110;
break;
case '7':
bin += 111;
break;
case '8':
bin += 1000;
break;
case '9':
bin += 1001;
break;
case 'a':
case 'A':
bin += 1010;
break;
case 'b':
case 'B':
bin += 1011;
break;
case 'c':
case 'C':
bin += 1100;
break;
case 'd':
case 'D':
bin += 1101;
break;
case 'e':
case 'E':
bin += 1110;
break;
case 'f':
case 'F':
bin += 1111;
break;
default:
printf("Invalid hexadecimal input.");
}
place = 10000;
}
place = 1;
/* Binary to octal conversion */
while(bin > 0)
{
rem = bin % 1000;
switch(rem)
{
case 0:
val = 0;
break;
case 1:
val = 1;
break;
case 10:
val = 2;
break;
case 11:
val = 3;
break;
case 100:
val = 4;
break;
case 101:
val = 5;
break;
case 110:
val = 6;
break;
case 111:
val = 7;
break;
}
octal = (val * place) + octal;
bin /= 1000;
place *= 10;
}
printf("Hexadecimal number = %s\n", hex);
printf("Octal number = %lld", octal);
return 0;
}

View File

@ -25,8 +25,10 @@ int main(void) {
else
number[i] = base + 1;
if (number[i] > base)
if (number[i] >= base){
printf("invalid number\n");
return 0;
}
}
for (j = 0; j < i; j++) {

View File

@ -0,0 +1,678 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct node{
int val;
struct node* par;
struct node* left;
struct node* right;
int color;
}Node;
// Create a new node
Node* newNode(int val, Node* par){
Node* create = (Node*)(malloc(sizeof(Node)));
create->val = val;
create->par = par;
create->left = NULL;
create->right = NULL;
create->color = 1;
}
// Check if the node is the leaf
int isLeaf(Node* n){
if(n->left == NULL && n->right == NULL){
return 1;
}
return 0;
}
// Left Rotate
Node* leftRotate(Node* node){
Node* parent = node->par;
Node* grandParent = parent->par;
parent->right = node->left;
if(node->left != NULL){
node->left->par = parent;
}
node->par = grandParent;
parent->par = node;
node->left = parent;
if(grandParent != NULL){
if(grandParent->right == parent){
grandParent->right = node;
}
else{
grandParent->left = node;
}
}
return node;
}
// Right Rotate
Node* rightRotate(Node* node){
Node* parent = node->par;
Node* grandParent = parent->par;
parent->left = node->right;
if(node->right != NULL){
node->right->par = parent;
}
node->par = grandParent;
parent->par = node;
node->right = parent;
if(grandParent != NULL){
if(grandParent->right == parent){
grandParent->right = node;
}
else{
grandParent->left = node;
}
}
return node;
}
// Check the node after the insertion step
void checkNode(Node* node){
// If the node is the root
if(node == NULL || node->par == NULL){
return;
}
Node* child = node;
//If it is a black node or its parent is a black node
if(node->color == 0 || (node->par)->color == 0){
// Dont Do Anything
return;
}
// Both parent and child are red
// Check For Uncle
Node* parent = node->par;
Node* grandParent = parent->par;
// If grandParent is NULL, then parent is the root.
// Just make the root black.
if(grandParent == NULL){
parent->color = 0;
return;
}
// If both the children of the grandParent are red
if(grandParent->right != NULL && (grandParent->right)->color == 1 && grandParent->left != NULL && (grandParent->left)->color == 1){
// Make the grandParent red and both of its children black
(grandParent->right)->color = 0;
(grandParent->left)->color = 0;
grandParent->color = 1;
return;
}
else{
// The only option left is rotation.
Node* greatGrandParent = grandParent->par;
// Right Case
if(grandParent->right == parent){
//Right Right Case
if(parent->right == node){
grandParent->right = parent->left;
if(parent->left != NULL){
(parent->left)->par = grandParent;
}
parent->left = grandParent;
grandParent->par = parent;
// Attach to existing Tree;
parent->par = greatGrandParent;
if(greatGrandParent != NULL){
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
greatGrandParent->left = parent;
}
else{
greatGrandParent->right = parent;
}
}
// Change the colors
parent->color = 0;
grandParent->color = 1;
}
else{ // Right Left Case
// First step -> Parent Child Rotation
parent->left = child->right;
if(child->right != NULL){
(child->right)->par = parent;
}
child->right = parent;
parent->par = child;
// Second step -> Child and GrandParent Rotation
grandParent->right = child->left;
if(child->left != NULL){
(child->left)->par = grandParent;
}
child->left = grandParent;
grandParent->par = child;
// Attach to the existing tree
child->par = greatGrandParent;
if(greatGrandParent != NULL){
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
greatGrandParent->left = child;
}
else{
greatGrandParent->right = child;
}
}
// Change The Colors
child->color = 0;
grandParent->color = 1;
}
}
else{ // Left Case
//Left Left Case
if(parent->left == node){
grandParent->left = parent->right;
if(parent->right != NULL){
(parent->right)->par = grandParent;
}
parent->right = grandParent;
grandParent->par = parent;
// Attach to existing Tree;
parent->par = greatGrandParent;
if(greatGrandParent != NULL){
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
greatGrandParent->left = parent;
}
else{
greatGrandParent->right = parent;
}
}
// Change the colors
parent->color = 0;
grandParent->color = 1;
}
else{ //Left Right Case
// First step -> Parent Child Rotation
parent->right = child->left;
if(child->left != NULL){
(child->left)->par = parent;
}
child->left = parent;
parent->par = child;
// Second step -> Child and GrandParent Rotation
grandParent->left = child->right;
if(child->right != NULL){
(child->right)->par = grandParent;
}
child->right = grandParent;
grandParent->par = child;
// Attach to the existing tree
child->par = greatGrandParent;
if(greatGrandParent != NULL){
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
greatGrandParent->left = child;
}
else{
greatGrandParent->right = child;
}
}
// Change The Colors
child->color = 0;
grandParent->color = 1;
}
}
}
}
// To insert a node in the existing tree
void insertNode(int val, Node** root){
Node* buffRoot = *root;
while(buffRoot){
if(buffRoot->val > val){
// Go left
if(buffRoot->left != NULL){
buffRoot = buffRoot->left;
}
else{
//Insert The Node
Node* toInsert = newNode(val, buffRoot);
buffRoot->left = toInsert;
buffRoot = toInsert;
//Check For Double Red Problems
break;
}
}
else{
// Go right
if(buffRoot->right != NULL){
buffRoot = buffRoot->right;
}
else{
//Insert The Node
Node* toInsert = newNode(val, buffRoot);
buffRoot->right = toInsert;
buffRoot = toInsert;
//Check For Double Red Problems
break;
}
}
}
while(buffRoot != *root){
checkNode(buffRoot);
if(buffRoot->par == NULL){
*root = buffRoot;
break;
}
buffRoot = buffRoot->par;
if(buffRoot == *root){
buffRoot->color = 0;
}
}
}
void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
if(toDelete == (*root)){
(*root)->color = 0;
return;
}
if(!delete && toDelete->color == 1){
if(!fromDirection){
if(toDelete->right != NULL){
toDelete->right->color = 1;
}
}
else{
if(toDelete->left != NULL){
toDelete->left->color = 1;
}
}
toDelete->color = 0;
return;
}
// Get the sibling for further inspection
Node* sibling;
Node* parent = toDelete->par;
int locateChild = 0; // 0 if toDeleted is left of its parent else 1
if(parent->right == toDelete){
sibling = parent->left;
locateChild = 1;
}
else{
sibling = parent->right;
}
//Case 2.1. i.e. if the any children of the sibling is red
if((sibling->right != NULL && sibling->right->color == 1) || (sibling->left != NULL && sibling->left->color == 1)){
if(sibling->right != NULL && sibling->right->color == 1){
// Sibling is left and child is right. i.e. LEFT RIGHT ROTATION
if(locateChild == 1){
int parColor = parent->color;
// Step 1: Left rotate sibling
sibling = leftRotate(sibling->right);
// Step 2: Right rotate updated sibling
parent = rightRotate(sibling);
// Check if the root is rotated
if(parent->par == NULL){
*root = parent;
}
// Step 3: Update the colors
parent->color = parColor;
parent->left->color = 0;
parent->right->color = 0;
// Delete the node (present at parent->right->right)
if(delete){
if(toDelete->left != NULL){
toDelete->left->par = parent->right;
}
parent->right->right = toDelete->left;
free(toDelete);
}
}
else{ // Sibling is right and child is also right. i.e. LEFT LEFT ROTATION
int parColor = parent->color;
// Left Rotate the sibling
parent = leftRotate(sibling);
// Check if the root is rotated
if(parent->par == NULL){
*root = parent;
}
// Update Colors
parent->color = parColor;
parent->left->color = 0;
parent->right->color = 0;
// Delete the node (present at parent->left->left)
if(delete){
if(toDelete->right != NULL){
toDelete->right->par = parent->left;
}
parent->left->left = toDelete->left;
free(toDelete);
}
}
}
else{
// Sibling is right and child is left. i.e. RIGHT LEFT ROTATION
if(locateChild == 0){
int parColor = parent->color;
// Step 1: Right rotate sibling
sibling = rightRotate(sibling->left);
// printf("%d - reached\n", sibling->val);
// return;
// Step 2: Left rotate updated sibling
parent = leftRotate(sibling);
// Check if the root is rotated
if(parent->par == NULL){
*root = parent;
}
// Step 3: Update the colors
parent->color = parColor;
parent->left->color = 0;
parent->right->color = 0;
// Delete the node (present at parent->left->left)
if(delete){
if(toDelete->right != NULL){
toDelete->right->par = parent->left;
}
parent->left->left = toDelete->right;
free(toDelete);
}
}
else{ // Sibling is left and child is also left. i.e. RIGHT RIGHT ROTATION
int parColor = parent->color;
// Right Rotate the sibling
parent = rightRotate(sibling);
// Check if the root is rotated
if(parent->par == NULL){
*root = parent;
}
// Update Colors
parent->color = parColor;
parent->left->color = 0;
parent->right->color = 0;
// Delete the node (present at parent->right->right)
if(delete){
if(toDelete->left != NULL){
toDelete->left->par = parent->right;
}
parent->right->right = toDelete->left;
free(toDelete);
}
}
}
}
else if(sibling->color == 0){ //Make the sibling red and recur for its parent
// Recolor the sibling
sibling->color = 1;
// Delete if necessary
if(delete){
if(locateChild){
toDelete->par->right = toDelete->left;
if(toDelete->left != NULL){
toDelete->left->par = toDelete->par;
}
}
else{
toDelete->par->left = toDelete->right;
if(toDelete->right != NULL){
toDelete->right->par = toDelete->par;
}
}
}
checkForCase2(parent, 0, locateChild, root);
}
else{ // Bring the sibling on top and apply 2.1 or 2.2 accordingly
if(locateChild){ //Right Rotate
toDelete->par->right = toDelete->left;
if(toDelete->left != NULL){
toDelete->left->par = toDelete->par;
}
parent = rightRotate(sibling);
// Check if the root is rotated
if(parent->par == NULL){
*root = parent;
}
parent->color = 0;
parent->right->color = 1;
checkForCase2(parent->right, 0, 1, root);
}
else{ // Left Rotate
toDelete->par->left = toDelete->right;
if(toDelete->right != NULL){
toDelete->right->par = toDelete->par;
}
parent = leftRotate(sibling);
// Check if the root is rotated
if(parent->par == NULL){
*root = parent;
}
printf("\nroot - %d - %d\n", parent->val, parent->left->val);
parent->color = 0;
parent->left->color = 1;
checkForCase2(parent->left, 0, 0, root);
}
}
}
// To delete a node from the tree
void deleteNode(int val, Node** root){
Node* buffRoot = *root;
//Search for the element in the tree
while(1){
if(val == buffRoot->val){
// Node Found
break;
}
if(val > buffRoot->val){
if(buffRoot->right != NULL){
buffRoot = buffRoot->right;
}
else{
printf("Node Not Found!!!");
return;
}
}
else{
if(buffRoot->left != NULL){
buffRoot = buffRoot->left;
}
else{
printf("Node Not Found!!!");
return;
}
}
}
Node* toDelete = buffRoot;
// Look for the leftmost of right node or right most of left node
if(toDelete->left != NULL){
toDelete = toDelete->left;
while(toDelete->right != NULL){
toDelete = toDelete->right;
}
}
else if(toDelete->right != NULL){
toDelete = toDelete->right;
while(toDelete->left != NULL){
toDelete = toDelete->left;
}
}
if(toDelete == *root){
*root = NULL;
return;
}
// Swap the values
buffRoot->val = toDelete->val;
toDelete->val = val;
// Checking for case 1
if(toDelete->color == 1 || (toDelete->left != NULL && toDelete->left->color == 1) || (toDelete->right != NULL && toDelete->right->color == 1)){
// if it is a leaf
if(toDelete->left == NULL && toDelete->right == NULL){
// Delete instantly
if(toDelete->par->left == toDelete){
toDelete->par->left = NULL;
}
else{
toDelete->par->right = NULL;
}
}
else{ // else its child should be red
// Check for the exitstence of left node
if(toDelete->left != NULL){
// The node should be right to its parent
toDelete->par->right = toDelete->left;
toDelete->left->par = toDelete->par;
toDelete->left->color = 1;
}
else{ // else the right node should be red
toDelete->par->left = toDelete->right;
toDelete->right->par = toDelete->par;
toDelete->right->color = 1;
}
}
// Remove the node from memory
free(toDelete);
}
else{ // Case 2
checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root);
}
}
void printInorder(Node* root){
if(root != NULL){
printInorder(root->left);
printf("%d c-%d ", root->val, root->color);
printInorder(root->right);
}
}
void checkBlack(Node* temp,int c){
if (temp==NULL){
printf("%d ",c);
return ;
}
if (temp->color==0){
c++;
}
checkBlack(temp->left,c);
checkBlack(temp->right,c);
}
int main(){
Node* root = NULL;
int scanValue, choice = 1;
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - ");
scanf("%d", &choice);
while(choice){
switch(choice){
case 1:
printf("\n\nPlease Enter A Value to insert - ");
scanf("%d", &scanValue);
if(root == NULL){
root = newNode(scanValue, NULL);
root->color = 0;
}
else{
insertNode(scanValue, &root);
}
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
break;
case 2:
printf("\n\nPlease Enter A Value to Delete - ");
scanf("%d", &scanValue);
deleteNode(scanValue, &root);
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
break;
case 3:
printf("\nInorder Traversel - ");
printInorder(root);
printf("\n\n");
// checkBlack(root,0);
// printf("\n");
break;
default:
if(root != NULL){
printf("Root - %d\n", root->val);
}
}
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - ");
scanf("%d", &choice);
}
}
// 32 12 50 53 1 2 3 4 5 6 7 8 9

View File

@ -0,0 +1,188 @@
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
//Assume max size of graph is 40 nodes
struct queue {
int items[SIZE];
int front;
int rear;
};
//Some declarations
struct queue* createQueue();
void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
int pollQueue(struct queue* q);
//Structure to create a graph node
struct node
{
int vertex;
struct node* next;
};
struct node* createNode(int);
//Graph data structure
struct Graph
{
int numVertices;
struct node** adjLists;
int* visited;
};
struct Graph* createGraph(int vertices);
void addEdge(struct Graph* graph, int src, int dest);
void printGraph(struct Graph* graph);
void bfs(struct Graph* graph, int startVertex);
int main()
{
int vertices,edges,source,i,src,dst;
printf("Enter the number of vertices\n");
scanf("%d",&vertices);
struct Graph* graph = createGraph(vertices);
printf("Enter the number of edges\n");
scanf("%d",&edges);
for(i=0; i<edges; i++)
{
printf("Edge %d \nEnter source: ",i+1);
scanf("%d",&src);
printf("Enter destination: ");
scanf("%d",&dst);
addEdge(graph, src, dst);
}
printf("Enter source of bfs\n");
scanf("%d",&source);
bfs(graph, source);
//Uncomment below part to get a ready-made example
/*struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph,0);*/
return 0;
}
void bfs(struct Graph* graph, int startVertex)
{
struct queue* q = createQueue();
//Add to visited list and put in queue
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
printf("Breadth first traversal from vertex %d is:\n",startVertex);
//Iterate while queue not empty
while(!isEmpty(q)){
printf("%d ",pollQueue(q));
int currentVertex = dequeue(q);
struct node* temp = graph->adjLists[currentVertex];
//Add all unvisited neighbours of current vertex to queue to be printed next
while(temp) {
int adjVertex = temp->vertex;
//Only add if neighbour is unvisited
if(graph->visited[adjVertex] == 0){
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
//Memory for a graph node
struct node* createNode(int v)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
//Allocates memory for graph data structure, in adjacency list format
struct Graph* createGraph(int vertices)
{
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
//Adds bidirectional edge to graph
void addEdge(struct Graph* graph, int src, int dest)
{
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src; comment it out for directed graph
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
//Allocates memory for our queue data structure
struct queue* createQueue()
{
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
//Checks for empty queue
int isEmpty(struct queue* q)
{
if(q->rear == -1)
return 1;
else
return 0;
}
//Inserts item at start of queue
void enqueue(struct queue* q, int value)
{
if(q->rear == SIZE-1)
printf("\nQueue is Full!!");
else {
if(q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}
//Returns item at front of queue and removes it from queue
int dequeue(struct queue* q)
{
int item;
if(isEmpty(q)){
printf("Queue is empty");
item = -1;
}
else{
item = q->items[q->front];
q->front++;
if(q->front > q->rear){
q->front = q->rear = -1;
}
}
return item;
}
//Returns element at front of queue
int pollQueue(struct queue *q)
{
return q->items[q->front];
}

View File

@ -0,0 +1,128 @@
#include <stdio.h>
#include <stdlib.h>
//A vertex of the graph
struct node
{
int vertex;
struct node* next;
};
//Some declarations
struct node* createNode(int v);
struct Graph
{
int numVertices;
int* visited;
struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists
};
struct Graph* createGraph(int);
void addEdge(struct Graph*, int, int);
void printGraph(struct Graph*);
void dfs(struct Graph*, int);
int main()
{
int vertices,edges,source,i,src,dst;
printf("Enter the number of vertices\n");
scanf("%d",&vertices);
struct Graph* graph = createGraph(vertices);
printf("Enter the number of edges\n");
scanf("%d",&edges);
for(i=0; i<edges; i++)
{
printf("Edge %d \nEnter source: ",i+1);
scanf("%d",&src);
printf("Enter destination: ");
scanf("%d",&dst);
addEdge(graph, src, dst);
}
printf("Enter source of DFS\n");
scanf("%d",&source);
printf("DFS from %d is:\n",source);
dfs(graph, source);
printf("\n");
//Uncomment below part to get a ready-made example
/*struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printf("DFS from 0 is:\n");
dfs(graph,0);
printf("\n");*/
return 0;
}
//Recursive dfs approach
void dfs(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
//Add vertex to visited list and print it
graph->visited[vertex] = 1;
printf("%d ", vertex);
//Recursively call the dfs function on all unvisited neighbours
while(temp!=NULL) {
int connectedVertex = temp->vertex;
if(graph->visited[connectedVertex] == 0) {
dfs(graph, connectedVertex);
}
temp = temp->next;
}
}
//Allocate memory for a node
struct node* createNode(int v)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
//Allocate memory for the entire graph structure
struct Graph* createGraph(int vertices)
{
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
//Creates a bidirectional graph
void addEdge(struct Graph* graph, int src, int dest)
{
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
//Utility function to see state of graph at a given time
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

View File

@ -0,0 +1,189 @@
// C program for Kruskal's algorithm to find Minimum Spanning Tree
// of a given connected, undirected and weighted graph
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// a structure to represent a weighted edge in graph
struct Edge
{
int src, dest, weight;
};
// a structure to represent a connected, undirected
// and weighted graph
struct Graph
{
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges.
// Since the graph is undirected, the edge
// from src to dest is also edge from dest
// to src. Both are counted as 1 edge here.
struct Edge* edge;
};
// Creates a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
// A structure to represent a subset for union-find
struct subset
{
int parent;
int rank;
};
// A utility function to find set of an element i
// (uses path compression technique)
int find(struct subset subsets[], int i)
{
// find root and make root as parent of i
// (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(struct subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high
// rank tree (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and
// increment its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// Compare two edges according to their weights.
// Used in qsort() for sorting an array of edges
int myComp(const void* a, const void* b)
{
struct Edge* a1 = (struct Edge*)a;
struct Edge* b1 = (struct Edge*)b;
return a1->weight > b1->weight;
}
// The main function to construct MST using Kruskal's algorithm
void KruskalMST(struct Graph* graph)
{
int V = graph->V;
struct Edge result[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges
// Step 1: Sort all the edges in non-decreasing
// order of their weight. If we are not allowed to
// change the given graph, we can create a copy of
// array of edges
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
// Allocate memory for creating V ssubsets
struct subset *subsets =
(struct subset*) malloc( V * sizeof(struct subset) );
// Create V subsets with single elements
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
// Number of edges to be taken is equal to V-1
while (e < V - 1 && i < graph->E)
{
// Step 2: Pick the smallest edge. And increment
// the index for next iteration
struct Edge next_edge = graph->edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
// If including this edge does't cause cycle,
// include it in result and increment the index
// of result for next edge
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
// print the contents of result[] to display the
// built MST
printf("Following are the edges in the constructed MST\n");
for (i = 0; i < e; ++i)
printf("%d -- %d == %d\n", result[i].src, result[i].dest,
result[i].weight);
return;
}
// Driver program to test above functions
int main()
{
/* Let us create following weighted graph
10
0--------1
| \ |
6| 5\ |15
| \ |
2--------3
4 */
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
struct Graph* graph = createGraph(V, E);
// add edge 0-1
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 10;
// add edge 0-2
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 6;
// add edge 0-3
graph->edge[2].src = 0;
graph->edge[2].dest = 3;
graph->edge[2].weight = 5;
// add edge 1-3
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;
// add edge 2-3
graph->edge[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight = 4;
KruskalMST(graph);
return 0;
}

View File

@ -0,0 +1,211 @@
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 40//Assume 40 nodes at max in graph
//A vertex of the graph
struct node
{
int vertex;
struct node* next;
};
//Some declarations
struct node* createNode(int v);
struct Graph
{
int numVertices;
int* visited;
struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists
};
//Structure to create a stack, necessary for topological sorting
struct Stack
{
int arr[MAX_SIZE];
int top;
};
struct Graph* createGraph(int);
void addEdge(struct Graph*, int, int);
void printGraph(struct Graph*);
struct Graph* transpose(struct Graph*);
void fillOrder(int,struct Graph*, struct Stack*);
void scc(struct Graph*);
void dfs(struct Graph*, int);
struct Stack* createStack();
void push(struct Stack*, int);
int pop(struct Stack*);
int main()
{
int vertices,edges,i,src,dst;
printf("Enter the number of vertices\n");
scanf("%d",&vertices);
struct Graph* graph = createGraph(vertices);
printf("Enter the number of edges\n");
scanf("%d",&edges);
for(i=0; i<edges; i++)
{
printf("Edge %d \nEnter source: ",i+1);
scanf("%d",&src);
printf("Enter destination: ");
scanf("%d",&dst);
addEdge(graph, src, dst);
}
printf("The strongly connected conponents are:\n");
scc(graph);
printf("\n");
//Uncomment below part to get a ready-made example
/*struct Graph* graph2 = createGraph(4);
addEdge(graph2, 0, 1);
addEdge(graph2, 1, 2);
addEdge(graph2, 2, 0);
addEdge(graph2, 2, 3);
printf("The strongly connected components are:\n");
scc(graph2);
printf("\n");*/
return 0;
}
//Creates a topological sorting of the graph
void fillOrder(int vertex, struct Graph* graph, struct Stack* stack)
{
graph->visited[vertex]=1;
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
//First add all dependents (that is, children) to stack
while(temp!=NULL) {
int connectedVertex = temp->vertex;
if(graph->visited[connectedVertex] == 0) {
fillOrder(connectedVertex, graph, stack);
}
temp=temp->next;
}
//and then add itself
push(stack,vertex);
}
//Transpose the adjacency list
struct Graph* transpose(struct Graph* g)
{
struct Graph* graph = createGraph(g->numVertices);//Number of vertices is same
int i=0;
for(i=0;i<g->numVertices;i++)
{
struct node* temp=g->adjLists[i];
while(temp!=NULL)
{
addEdge(graph,temp->vertex,i);//Reverse all edges
temp=temp->next;
}
}
return graph;
}
//Recursive dfs aproach
void dfs(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
//Add vertex to visited list and print it
graph->visited[vertex] = 1;
printf("%d ", vertex);
//Recursively call the dfs function on all unvisited neighbours
while(temp!=NULL) {
int connectedVertex = temp->vertex;
if(graph->visited[connectedVertex] == 0) {
dfs(graph, connectedVertex);
}
temp = temp->next;
}
}
//Strongly connected components
void scc(struct Graph* graph)
{
//Step I: Create a topological sort of the graph and store it in a stack
struct Stack* stack=createStack();
int i=0;
for(i=0;i<graph->numVertices;i++)
{
//Execute topological sort on all elements
if(graph->visited[i]==0)
{
fillOrder(i,graph,stack);
}
}
//Step 2: Get the transpose graph
struct Graph* graphT=transpose(graph);
//Step 3: Perform a simple dfs by popping nodes from stack
while(stack->top!=-1)
{
int v=pop(stack);
if(graphT->visited[v]==0)
{
dfs(graphT,v);
printf("\n");
}
}
}
//Allocate memory for a node
struct node* createNode(int v)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
//Allocate memory for the entire graph structure
struct Graph* createGraph(int vertices)
{
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
//Creates a unidirectional graph
void addEdge(struct Graph* graph, int src, int dest)
{
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}
//Utility function to see state of graph at a given time
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
//Creates a stack
struct Stack* createStack()
{
struct Stack* stack=malloc(sizeof(struct Stack));
stack->top=-1;
}
//Pushes element into stack
void push(struct Stack* stack,int element)
{
stack->arr[++stack->top]=element;//Increment then add, as we start from -1
}
//Removes element from stack, or returns INT_MIN if stack empty
int pop(struct Stack* stack)
{
if(stack->top==-1)
return INT_MIN;
else
return stack->arr[stack->top--];
}

View File

@ -0,0 +1,164 @@
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 40//Assume 40 nodes at max in graph
//A vertex of the graph
struct node
{
int vertex;
struct node* next;
};
//Some declarations
struct node* createNode(int v);
struct Graph
{
int numVertices;
int* visited;
struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists
};
//Structure to create a stack, necessary for topological sorting
struct Stack
{
int arr[MAX_SIZE];
int top;
};
struct Graph* createGraph(int);
void addEdge(struct Graph*, int, int);
void printGraph(struct Graph*);
void topologicalSortHelper(int,struct Graph*, struct Stack*);
void topologicalSort(struct Graph*);
struct Stack* createStack();
void push(struct Stack*, int);
int pop(struct Stack*);
int main()
{
int vertices,edges,i,src,dst;
printf("Enter the number of vertices\n");
scanf("%d",&vertices);
struct Graph* graph = createGraph(vertices);
printf("Enter the number of edges\n");
scanf("%d",&edges);
for(i=0; i<edges; i++)
{
printf("Edge %d \nEnter source: ",i+1);
scanf("%d",&src);
printf("Enter destination: ");
scanf("%d",&dst);
addEdge(graph, src, dst);
}
printf("One topological sort order is:\n");
topologicalSort(graph);
printf("\n");
//Uncomment below part to get a ready-made example
/*struct Graph* graph2 = createGraph(4);
addEdge(graph2, 0, 1);
addEdge(graph2, 0, 2);
addEdge(graph2, 1, 2);
addEdge(graph2, 2, 3);
printf("One topological sort is:\n");
topologicalSort(graph2);
printf("\n");*/
return 0;
}
void topologicalSortHelper(int vertex, struct Graph* graph, struct Stack* stack)
{
graph->visited[vertex]=1;
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
//First add all dependents (that is, children) to stack
while(temp!=NULL) {
int connectedVertex = temp->vertex;
if(graph->visited[connectedVertex] == 0) {
topologicalSortHelper(connectedVertex, graph, stack);
}
temp=temp->next;
}
//and then add itself
push(stack,vertex);
}
//Recursive topologial sort approach
void topologicalSort(struct Graph* graph)
{
struct Stack* stack=createStack();
int i=0;
for(i=0;i<graph->numVertices;i++)
{
//Execute topological sort on all elements
if(graph->visited[i]==0)
{
topologicalSortHelper(i,graph,stack);
}
}
while(stack->top!=-1)
printf("%d ",pop(stack));
}
//Allocate memory for a node
struct node* createNode(int v)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
//Allocate memory for the entire graph structure
struct Graph* createGraph(int vertices)
{
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
//Creates a unidirectional graph
void addEdge(struct Graph* graph, int src, int dest)
{
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}
//Utility function to see state of graph at a given time
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
//Creates a stack
struct Stack* createStack()
{
struct Stack* stack=malloc(sizeof(struct Stack));
stack->top=-1;
}
//Pushes element into stack
void push(struct Stack* stack,int element)
{
stack->arr[++stack->top]=element;//Increment then add, as we start from -1
}
//Removes element from stack, or returns INT_MIN if stack empty
int pop(struct Stack* stack)
{
if(stack->top==-1)
return INT_MIN;
else
return stack->arr[stack->top--];
}

View File

@ -0,0 +1,121 @@
#include<stdio.h>
#include<stdlib.h>
typedef struct max_heap{
int *p;
int size;
int count;
}Heap;
Heap* create_heap(Heap* heap); /*Creates a max_heap structure and returns a pointer to the struct*/
void down_heapify(Heap* heap, int index);/*Pushes an element downwards in the heap to find its correct position*/
void up_heapify(Heap* heap, int index);/*Pushes an element upwards in the heap to find its correct position*/
void push(Heap* heap, int x);/*Inserts an element in the heap*/
void pop(Heap* heap);/*Removes the top element from the heap*/
int top(Heap* heap);/*Returns the top element of the heap or returns INT_MIN if heap is empty*/
int empty(Heap* heap);/*Checks if heap is empty*/
int size(Heap* heap);/*Returns the size of heap*/
int main(){
Heap* head = create_heap(head);
push(head, 10);
printf("Pushing element : 10\n");
push(head, 3);
printf("Pushing element : 3\n");
push(head, 2);
printf("Pushing element : 2\n");
push(head, 8);
printf("Pushing element : 8\n");
printf("Top element = %d \n", top(head));
push(head, 1);
printf("Pushing element : 1\n");
push(head, 7);
printf("Pushing element : 7\n");
printf("Top element = %d \n", top(head));
pop(head);
printf("Popping an element.\n");
printf("Top element = %d \n", top(head));
pop(head);
printf("Popping an element.\n");
printf("Top element = %d \n", top(head));
printf("\n");
return 0;
}
Heap* create_heap(Heap* heap){
heap = (Heap *)malloc(sizeof(Heap));
heap->size = 1;
heap->p = (int *)malloc(heap->size*sizeof(int));
heap->count = 0;
}
void down_heapify(Heap* heap, int index){
if(index>=heap->count)return;
int left = index*2+1;
int right = index*2+2;
int leftflag = 0, rightflag = 0;
int maximum = *((heap->p)+index);
if(left<heap->count && maximum<*((heap->p)+left)){
maximum = *((heap->p)+left);
leftflag = 1;
}
if(right<heap->count && maximum<*((heap->p)+right)){
maximum = *((heap->p)+right);
leftflag = 0;
rightflag = 1;
}
if(leftflag){
*((heap->p)+left) = *((heap->p)+index);
*((heap->p)+index) = maximum;
down_heapify(heap, left);
}
if(rightflag){
*((heap->p)+right) = *((heap->p)+index);
*((heap->p)+index) = maximum;
down_heapify(heap, right);
}
}
void up_heapify(Heap* heap, int index){
int parent = (index-1)/2;
if(parent<0)return;
if(*((heap->p)+index)>*((heap->p)+parent)){
int temp = *((heap->p)+index);
*((heap->p)+index) = *((heap->p)+parent);
*((heap->p)+parent) = temp;
up_heapify(heap, parent);
}
}
void push(Heap* heap, int x){
if(heap->count>=heap->size)return;
*((heap->p)+heap->count) = x;
heap->count++;
if(4*heap->count >= 3*heap->size){
heap->size *= 2;
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
}
up_heapify(heap, heap->count - 1);
}
void pop(Heap* heap){
if(heap->count==0)return;
heap->count--;
int temp = *((heap->p)+heap->count);
*((heap->p)+heap->count) = *(heap->p);
*(heap->p) = temp;
down_heapify(heap, 0);
if(4*heap->count<=heap->size){
heap->size /= 2;
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
}
}
int top(Heap* heap){
if(heap->count!=0)return *(heap->p);
else return INT_MIN;
}
int empty(Heap* heap){
if(heap->count!=0)return 0;
else return 1;
}
int size(Heap* heap){
return heap->count;
}

View File

@ -0,0 +1,121 @@
#include<stdio.h>
#include<stdlib.h>
typedef struct min_heap{
int *p;
int size;
int count;
}Heap;
Heap* create_heap(Heap* heap); /*Creates a min_heap structure and returns a pointer to the struct*/
void down_heapify(Heap* heap, int index);/*Pushes an element downwards in the heap to find its correct position*/
void up_heapify(Heap* heap, int index);/*Pushes an element upwards in the heap to find its correct position*/
void push(Heap* heap, int x);/*Inserts an element in the heap*/
void pop(Heap* heap);/*Removes the top element from the heap*/
int top(Heap* heap);/*Returns the top element of the heap or returns INT_MIN if heap is empty*/
int empty(Heap* heap);/*Checks if heap is empty*/
int size(Heap* heap);/*Returns the size of heap*/
int main(){
Heap* head = create_heap(head);
push(head, 10);
printf("Pushing element : 10\n");
push(head, 3);
printf("Pushing element : 3\n");
push(head, 2);
printf("Pushing element : 2\n");
push(head, 8);
printf("Pushing element : 8\n");
printf("Top element = %d \n", top(head));
push(head, 1);
printf("Pushing element : 1\n");
push(head, 7);
printf("Pushing element : 7\n");
printf("Top element = %d \n", top(head));
pop(head);
printf("Popping an element.\n");
printf("Top element = %d \n", top(head));
pop(head);
printf("Popping an element.\n");
printf("Top element = %d \n", top(head));
printf("\n");
return 0;
}
Heap* create_heap(Heap* heap){
heap = (Heap *)malloc(sizeof(Heap));
heap->size = 1;
heap->p = (int *)malloc(heap->size*sizeof(int));
heap->count = 0;
}
void down_heapify(Heap* heap, int index){
if(index>=heap->count)return;
int left = index*2+1;
int right = index*2+2;
int leftflag = 0, rightflag = 0;
int minimum = *((heap->p)+index);
if(left<heap->count && minimum>*((heap->p)+left)){
minimum = *((heap->p)+left);
leftflag = 1;
}
if(right<heap->count && minimum>*((heap->p)+right)){
minimum = *((heap->p)+right);
leftflag = 0;
rightflag = 1;
}
if(leftflag){
*((heap->p)+left) = *((heap->p)+index);
*((heap->p)+index) = minimum;
down_heapify(heap, left);
}
if(rightflag){
*((heap->p)+right) = *((heap->p)+index);
*((heap->p)+index) = minimum;
down_heapify(heap, right);
}
}
void up_heapify(Heap* heap, int index){
int parent = (index-1)/2;
if(parent<0)return;
if(*((heap->p)+index)<*((heap->p)+parent)){
int temp = *((heap->p)+index);
*((heap->p)+index) = *((heap->p)+parent);
*((heap->p)+parent) = temp;
up_heapify(heap, parent);
}
}
void push(Heap* heap, int x){
if(heap->count>=heap->size)return;
*((heap->p)+heap->count) = x;
heap->count++;
if(4*heap->count >= 3*heap->size){
heap->size *= 2;
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
}
up_heapify(heap, heap->count - 1);
}
void pop(Heap* heap){
if(heap->count==0)return;
heap->count--;
int temp = *((heap->p)+heap->count);
*((heap->p)+heap->count) = *(heap->p);
*(heap->p) = temp;
down_heapify(heap, 0);
if(4*heap->count<=heap->size){
heap->size /= 2;
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
}
}
int top(Heap* heap){
if(heap->count!=0)return *(heap->p);
else return INT_MIN;
}
int empty(Heap* heap){
if(heap->count!=0)return 0;
else return 1;
}
int size(Heap* heap){
return heap->count;
}

View File

@ -0,0 +1,12 @@
CC = gcc
CFLAGS = -g -c -Wall
all: main
main: main.o list.o
$(CC) -g main.o list.o -o main
list.o: list.c
$(CC) $(CFLAGS) list.c
clean:
rm *o main

View File

@ -0,0 +1,73 @@
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "list.h"
#define L List_T
/* Initial list */
L List_init (void) {
L list;
list = (L) malloc(sizeof(L));
list->next = NULL;
return list;
}
/* Push an element into top of the list */
L List_push(L list, void *val) {
L new_elem = (L)malloc(sizeof(L));
new_elem->val = val;
new_elem->next = list;
return new_elem;
}
/* Length of list */
int List_length(L list) {
int n;
for(n = 0; list; list=list->next)
n++;
return n;
}
/* Convert list to array */
void **List_toArray(L list) {
int i, n = List_length(list);
void **array = (void **)malloc((n+1) *sizeof(*array));
for(i = 0; i < n; i++) {
array[i] = list->val;
list = list->next;
}
array[i] = NULL;
return array;
}
/* Create and return a list */
L List_list(L list, void *val, ...) {
va_list ap;
L *p = &list;
va_start(ap, val);
for(; val; val = va_arg(ap, void *)) {
*p = malloc(sizeof(L));
(*p)->val = val;
p = &(*p)->next;
}
*p = NULL;
va_end(ap);
return list;
}
/* Append 2 lists together */
L List_append(L list, L tail) {
L *p = &list;
while((*p)->next) {
p = &(*p)->next;
}
*p = tail;
return list;
}

View File

@ -0,0 +1,23 @@
#ifndef __LIST__
#define __LIST__
#define L List_T
typedef struct L *L;
struct L {
void *val;
L next;
};
extern L List_init(void);
extern L List_push(L list, void *val);
extern int List_length(L list);
extern void **List_toArray(L list);
extern L List_append(L list, L tail);
extern L List_list(L list, void *val, ...);
/* TODO */
extern L List_copy(L list);
extern int List_pop(L *list);
#undef L
#endif

View File

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "list.h"
void print_list(char **array) {
int i;
for( i = 0; array[i]; i++)
printf("%s", array[i]);
printf("\n");
}
int main() {
List_T list1, list2, list3;
char **str1 = (char **)malloc(100* sizeof(char *));
list1 = List_init();
list1 = List_push(list1, "Dang ");
list1 = List_push(list1, "Hoang ");
list1 = List_push(list1, "Hai ");
printf("List 1: ");
str1 = (char **)List_toArray(list1);
print_list(str1);
list2 = List_init();
list2 = List_list(list2, "Mentor ", "Graphics ", "Siemens", NULL);
printf("List 2: ");
print_list((char **)List_toArray(list2));
list3 = List_append(list1, list2);
printf("Test append list2 into list1: ");
print_list((char **)List_toArray(list3));
return 0;
}

View File

@ -88,6 +88,7 @@ void push(int x) {
tmp->data = x;
tmp->next = NULL;
tmp->pre = head;
head->next = tmp;
head = tmp;
}
++count;
@ -104,8 +105,10 @@ int pop() {
} else {
returnData = head->data;
if(head->pre == NULL)
if(head->pre == NULL){
free(head);
head = NULL;
}
else {
head = head->pre;
free(head->next);

View File

@ -1,4 +1,4 @@
# Simple generic Stack
# Simple generic Stack
This is a modular generic stack data-structure. The stack is self growing.
@ -6,7 +6,8 @@ This is a modular generic stack data-structure. The stack is self growing.
* stack-Header file for import.
* stack.c implementation of the stack
* main.c framework program for testing.
* main.c framework program for testing.
* stack_linkedlist: Another stack implementation by linkedlist
You need to only import the **stack.h**
@ -18,7 +19,7 @@ Initializes the stack with a capacity of 10 elements.
``` void push(void * object); ```
pushs the argument onto the stack
pushs the argument onto the stack
``` void * pop(); ```

View File

@ -0,0 +1,99 @@
//program for stack using array
#include <stdio.h>
void push();
void pop();
void peek();
void update();
int a[100], top = -1;
int main()
{
int x;
while (1)
{
printf("\n0.exit");
printf("\n1.push");
printf("\n2.pop");
printf("\n3.peek");
printf("\n4.update");
printf("\nenter your choice? ");
scanf("%d", &x);
switch (x)
{
case 0:
return 0;
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
update();
break;
default:
printf("\ninvalid choice");
}
}
return (0);
}
//function for pushing the element
void push()
{
int n = 0;
printf("\nenter the value to insert? ");
scanf("%d", &n);
top += 1;
a[top] = n;
}
//function for poping the element out
void pop()
{
if (top == -1)
{
printf("\nstack is empty");
}
else
{
int item;
item = a[top];
top -= 1;
printf("\npoped item is %d ", item);
}
}
//function for peeping the element from top of the stack
void peek()
{
if (top >= 0)
printf("\n the top element is %d", a[top]);
else
printf("\nstack is empty");
}
//function to update the element of stack
void update()
{
int i, n;
printf("\nenter the position to update? ");
scanf("%d", &i);
printf("\nenter the item to insert? ");
scanf("%d", &n);
if (top - i + 1 < 0)
{
printf("\nunderflow condition");
}
else
{
a[top - i + 1] = n;
}
}

View File

@ -0,0 +1,115 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define SIZE 100
struct node
{
char data;
struct node *link;
};
int c = 0; // c used as counter to check if stack is empty or not
struct node *head; //declaring head pointer globally assigned to NULL
void push(char x) //function for pushing
{
struct node *p = head, *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = x;
if (head == NULL) //will be execute only one time i.e, 1st time push is called
{
head = temp;
p = head;
p->link = NULL;
c++;
}
else
{
temp->link = p;
p = temp;
head = p;
c++;
}
}
char pop(void) //function for pop
{
char x;
struct node *p = head;
x = p->data;
head = p->link;
free(p);
c--;
return x;
}
int isBalanced(char *s)
{
int i = 0;
char x;
while (s[i] != '\0') //loop for covering entire string of brackets
{
// printf("\t s[i]=%c\n", s[i]); //DEBUG
if (s[i] == '{' || s[i] == '(' || s[i] == '[') //if opening bracket then push
push(s[i]);
else
{
if (c <= 0) //i.e, stack is empty as only opening brackets are added to stack
return 0;
x = pop();
if (x == '{' && s[i] != '}')
return 0;
if (x == '[' && s[i] != ']')
return 0;
if (x == '(' && s[i] != ')')
return 0;
}
i++;
}
//at end if stack is empy which means whole process has been performed correctly so return 1
return (c == 0) ? 1 : 0;
}
void destroyStack(void)
{
struct node *p = head;
if (c > 0)
{
while (p->link)
{
struct node *tmp = p;
p = p->link;
free(tmp);
}
c = 0;
}
}
int main(void)
{
int t;
printf("\t\tBalanced parenthesis\n\n");
printf("\nPlease enter the number of processing rounds? ");
scanf("%d", &t);
for (int a0 = 0; a0 < t; a0++)
{
char s[SIZE];
printf("\nPlease enter the expression? ");
scanf("%s", s);
if (isBalanced(s))
printf("\nYES\n");
else
printf("\nNO\n");
/* tidy up stack for new round */
destroyStack();
}
return 0;
}

View File

@ -42,7 +42,7 @@ void initStack()
grow: increases the stack by 10 elements.
This utility function isn't part of the public interface
*/
void grow()
void grow()
{
max += 10; /* increases the capacity */
@ -54,8 +54,9 @@ void grow()
{
*(tmp + i) = *(array + i);
}
array = tmp; /* setups the new one as basis */
/*free the memory */
free(array);
array = tmp;
}
/* push: pushs the argument onto the stack */
@ -133,4 +134,4 @@ void *top()
{
/* offset address points to the top element */
return array[offset];
}
}

View File

@ -0,0 +1,12 @@
CC = gcc
CFLAGS = -c -Wall
all: main
main: main.o stack.o
$(CC) main.o stack.o -o main
stack.o: stack.c
$(CC) $(CFLAGS) stack.c
clean:
rm *o main

View File

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
int main() {
Stack_T stk;
stk = Stack_init();
Stack_push(stk, (int *) 1);
Stack_push(stk, (int *) 2);
Stack_push(stk, (int *) 3);
Stack_push(stk, (int *) 4);
printf("Size: %d\n", Stack_size(stk));
Stack_print(stk);
Stack_pop(stk);
printf("Stack after popping: \n");
Stack_print(stk);
Stack_pop(stk);
printf("Stack after popping: \n");
Stack_print(stk);
return 0;
}

View File

@ -0,0 +1,79 @@
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
#define T Stack_T
typedef struct elem {
void *val;
struct elem *next;
} elem_t;
struct T {
int count;
elem_t *head;
};
/* Initial stack */
T Stack_init (void) {
T stack;
stack = (T) malloc(sizeof(T));
stack->count = 0;
stack->head = NULL;
return stack;
}
/* Check empty stack*/
int Stack_empty(T stack) {
assert(stack);
return stack->count == 0;
}
/* Return size of the stack */
int Stack_size(T stack) {
assert(stack);
return stack->count;
}
/* Push an element into the stack */
void Stack_push(T stack, void *val) {
elem_t *t;
assert(stack);
t = (elem_t *) malloc(sizeof(elem_t));
t->val = val;
t->next = stack->head;
stack->head = t;
stack->count++;
}
/* Pop an element out of the stack */
void *Stack_pop(T stack) {
void *val;
elem_t *t;
assert(stack);
assert(stack->count > 0);
t = stack->head;
stack->head = t->next;
stack->count--;
val = t->val;
free(t);
return val;
}
/* Print all elements in the stack */
void Stack_print(Stack_T stack) {
assert(stack);
int i, size = Stack_size(stack);
elem_t *current_elem = stack->head;
printf("Stack [Top --- Bottom]: ");
for(i = 0; i < size; ++i) {
printf("%p ", (int *)current_elem->val);
current_elem = current_elem->next;
}
printf("\n");
}

View File

@ -0,0 +1,15 @@
#ifndef __STACK__
#define __STACK__
#define T Stack_T
typedef struct T *T;
extern T Stack_init (void);
extern int Stack_size (T stack);
extern int Stack_empty (T stack);
extern void Stack_push (T stack, void *val);
extern void *Stack_pop (T stack);
extern void Stack_print (T stack);
#undef T
#endif

View File

@ -5,6 +5,7 @@
const char *hello(void)
{
char * ans = malloc(sizeof(char) * strlen("Hello, World!"));
if (!ans) return NULL;
strcpy(ans,"Hello, World!");
/* string is pointer of the first character */

View File

@ -4,4 +4,5 @@ Overview files **hash.h** and **hash.c**
* sdbm
* djb2
* xor8 (8 bit)
* adler_32 (32 bit)
* adler_32 (32 bit)
* crc32 (32 bit)

View File

@ -60,4 +60,21 @@ int adler_32(char s[])
i++;
}
return (b << 16) | a;
}
/* crc32 Hash-Algorithm*/
#include <inttypes.h>
uint32_t crc32(char* data){
int i = 0;
uint32_t crc = 0xffffffff;
while(data[i] != '\0'){
uint8_t byte = data[i];
crc = crc ^ byte;
for(int j = 8; j > 0; --j)
crc = (crc >> 1) ^ (0xEDB88320 & ( -(crc & 1)));
i++;
}
return crc ^ 0xffffffff;
}

View File

@ -40,4 +40,12 @@ char xor8(char[]);
*/
int adler_32(char[]);
/*
crc32: implements the crc-32 checksum-algorithm
returns the crc-32 checksum
*/
int crc32(char[]);
#endif

View File

@ -15,6 +15,8 @@ int main(void)
printf("djb2: %s --> %lld\n", s, djb2(s));
printf("xor8: %s --> %i\n", s, xor8(s)); /* 8 bit */
printf("adler_32: %s --> %i\n", s, adler_32(s)); /* 32 bit */
printf("crc32: %s --> %i\n", s, crc32(s));
return 0;
}

91
leetcode/README.md Normal file
View File

@ -0,0 +1,91 @@
LeetCode
========
### LeetCode Algorithm
| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|1|[Two Sum](https://leetcode.com/problems/two-sum/) | [C](./src/1.c)|Easy|
|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C](./src/2.c)|Medium|
|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C](./src/3.c)|Medium|
|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [C](./src/4.c)|Hard|
|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C](./src/7.c)|Easy|
|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi) | [C](./src/8.c)|Medium|
|9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C](./src/9.c)|Easy|
|11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [C](./src/11.c)|Medium|
|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman) | [C](./src/12.c)|Medium|
|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C](./src/13.c)|Easy|
|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [C](./src/20.c)|Easy|
|21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [C](./src/21.c)|Easy|
|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [C](./src/24.c)|Medium|
|26|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [C](./src/26.c)|Easy|
|27|[Remove Element](https://leetcode.com/problems/remove-element/) | [C](./src/27.c)|Easy|
|28|[Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C](./src/28.c)|Easy|
|29|[Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C](./src/29.c)|Medium|
|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C](./src/35.c)|Easy|
|53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [C](./src/53.c)|Easy|
|66|[Plus One](https://leetcode.com/problems/plus-one/) | [C](./src/66.c)|Easy|
|82|[Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | [C](./src/82.c)|Medium|
|83|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | [C](./src/83.c)|Easy|
|94|[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C](./src/94.c)|Medium|
|101|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) | [C](./src/101.c)|Easy|
|104|[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [C](./src/104.c)|Easy|
|108|[Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [C](./src/108.c)|Easy|
|109|[Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [C](./src/109.c)|Medium|
|110|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [C](./src/110.c)|Easy|
|112|[Path Sum](https://leetcode.com/problems/path-sum/) | [C](./src/112.c)|Easy|
|121|[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | [C](./src/121.c)|Easy|
|125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C](./src/125.c)|Easy|
|136|[Single Number](https://leetcode.com/problems/single-number/) | [C](./src/136.c)|Easy|
|141|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [C](./src/141.c)|Easy|
|142|[Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) | [C](./src/142.c)|Medium|
|153|[Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [C](./src/153.c)|Medium|
|160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | [C](./src/160.c)|Easy|
|169|[Majority Element](https://leetcode.com/problems/majority-element/) | [C](./src/169.c)|Easy|
|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C](./src/173.c)|Medium|
|190|[Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [C](./src/190.c)|Easy|
|191|[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [C](./src/191.c)|Easy|
|201|[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C](./src/201.c)|Medium|
|203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) | [C](./src/203.c)|Easy|
|206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [C](./src/206.c)|Easy|
|215|[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C](./src/215.c)|Medium|
|217|[Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C](./src/217.c)|Easy|
|226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C](./src/226.c)|Easy|
|231|[Power of Two](https://leetcode.com/problems/power-of-two/) | [C](./src/231.c)|Easy|
|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | [C](./src/234.c)|Easy|
|242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/) | [C](./src/242.c)|Easy|
|268|[Missing Number](https://leetcode.com/problems/missing-number/) | [C](./src/268.c)|Easy|
|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C](./src/278.c)|Easy|
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C](./src/283.c)|Easy|
|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [C](./src/287.c)|Medium|
|344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C](./src/344.c)|Easy|
|367|[Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/) | [C](./src/367.c)|Easy|
|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C](./src/387.c)|Easy|
|389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C](./src/389.c)|Easy|
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C](./src/404.c)|Easy|
|442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C](./src/442.c)|Medium|
|461|[Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C](./src/461.c) |Easy|
|476|[Number Complement](https://leetcode.com/problems/number-complement/) | [C](./src/476.c)|Easy|
|509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [C](./src/509.c)|Easy|
|520|[Detect Capital](https://leetcode.com/problems/detect-capital/) | [C](./src/520.c)|Easy|
|561|[Array Partition I](https://leetcode.com/problems/array-partition-i/) | [C](./src/561.c)|Easy|
|617|[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | [C](./src/617.c)|Easy|
|647|[Palindromic Substring](https://leetcode.com/problems/palindromic-substrings/) | [C](./src/647.c)|Medium|
|674|[Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C](./src/674.c)|Easy|
|700|[Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [C](./src/700.c)|Easy|
|701|[Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | [C](./src/701.c)|Medium|
|704|[Binary Search](https://leetcode.com/problems/binary-search/) | [C](./src/704.c)|Easy|
|709|[To Lower Case](https://leetcode.com/problems/to-lower-case/) | [C](./src/709.c)|Easy|
|771|[Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C](./src/771.c)|Easy|
|852|[Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [C](./src/852.c)|Easy|
|876|[Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [C](./src/876.c)|Easy|
|905|[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C](./src/905.c)|Easy|
|917|[Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/) | [C](./src/917.c)|Easy|
|938|[Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c)|Easy|
|965|[Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c)|Easy|
|977|[Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c)|Easy|
|1089|[Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [C](./src/1089.c)|Easy|
|1184|[Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c)|Easy|
|1189|[Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c)|Easy|
|1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C](./src/1207.c)|Easy|

14
leetcode/src/1.c Normal file
View File

@ -0,0 +1,14 @@
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, j;
int *ret = calloc(2, sizeof(int));
for (i = 0; i < numsSize; i++) {
int key = target - nums[i];
for (j = i + 1; j < numsSize; j++)
if (nums[j] == key) {
ret[0] = i;
ret[1] = j;
}
}
*returnSize = 2;
return ret;
}

20
leetcode/src/101.c Normal file
View File

@ -0,0 +1,20 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool checkSymmetric(struct TreeNode *left, struct TreeNode *right) {
if (!left || !right)
return left == right;
if (left->val != right->val)
return 0;
return checkSymmetric(left->left, right->right) && checkSymmetric(left->right, right->left);
}
bool isSymmetric(struct TreeNode* root){
return root == NULL || checkSymmetric(root->left, root->right);
}

22
leetcode/src/104.c Normal file
View File

@ -0,0 +1,22 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxval(int a, int b) {
if (a > b)
return a;
else
return b;
}
int maxDepth(struct TreeNode* root){
if (root == NULL)
return 0;
else
return 1 + maxval(maxDepth(root->left), maxDepth(root->right));
}

29
leetcode/src/108.c Normal file
View File

@ -0,0 +1,29 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* convertBST(int *nums, int left, int right) {
if (left > right)
return NULL;
else {
int mid = (right + left) / 2;
struct TreeNode *new_val = malloc(sizeof(struct TreeNode));
new_val->val = nums[mid];
new_val->left = convertBST(nums, left, mid - 1);
new_val->right = convertBST(nums, mid + 1, right);
return new_val;
}
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
if(numsSize == 0)
return NULL;
else
return convertBST(nums, 0, numsSize -1);
}

20
leetcode/src/1089.c Normal file
View File

@ -0,0 +1,20 @@
void duplicateZeros(int* arr, int arrSize){
int i, start = 0;
int *tmp = malloc(arrSize * sizeof(int));
/* Copy arr into tmp arr */
for(i = 0; i < arrSize; i++) {
tmp[i] = arr[i];
}
i = 0;
for(start = 0; start < arrSize; start++) {
arr[start] = tmp[i];
if(tmp[i] == 0) {
start++;
if (start < arrSize)
arr[start] = 0;
}
i++;
}
}

21
leetcode/src/109.c Normal file
View File

@ -0,0 +1,21 @@
struct TreeNode* buildBST(struct ListNode* head, struct ListNode* tail) {
if(head == tail)
return NULL;
struct ListNode* slow = head, *fast = head;
while(fast != tail && fast->next != tail) {
fast = fast->next->next;
slow = slow->next;
}
struct TreeNode* node = malloc(sizeof(struct TreeNode));
node->val = slow->val;
node->left = buildBST(head, slow);
node->right = buildBST(slow->next, tail);
return node;
}
struct TreeNode* sortedListToBST(struct ListNode* head){
if (!head)
return NULL;
else
return buildBST(head, NULL);
}

30
leetcode/src/11.c Normal file
View File

@ -0,0 +1,30 @@
//Fucntion to calculate min of values a and b
int min(int a, int b){
return ((a<b)?a:b);
}
//Two pointer approach to find maximum container area
int maxArea(int* height, int heightSize){
//Start with maximum container width
int start = 0;
int end = heightSize-1;
int res = 0;
while(start<end){
//Calculate current area by taking minimum of two heights
int currArea = (end-start)*min(height[start],height[end]);
if(currArea>res)
res = currArea;
if(height[start]<height[end])
start = start + 1;
else
end = end - 1;
}
return res;
}

19
leetcode/src/110.c Normal file
View File

@ -0,0 +1,19 @@
int max(int a, int b) {
return a >= b ? a : b;
}
int height(struct TreeNode* root) {
if (root == NULL)
return 0;
else
return 1 + max(height(root->left), height(root->right));
}
bool isBalanced(struct TreeNode* root){
if (root == NULL)
return 1;
int left = height(root->left);
int right = height(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}

7
leetcode/src/112.c Normal file
View File

@ -0,0 +1,7 @@
bool hasPathSum(struct TreeNode* root, int sum) {
if (root == NULL)
return 0;
if (!root->left && !root->right && sum - root->val == 0)
return 1;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}

16
leetcode/src/1184.c Normal file
View File

@ -0,0 +1,16 @@
int distanceBetweenBusStops(int* distance, int distanceSize, int start, int destination){
int sum1 = 0, sum2 = 0;
if (start > destination) {
int tmp = start;
start = destination;
destination = tmp;
}
for (auto i = 0; i < distanceSize; ++i) {
if (i >= start && i < destination)
sum1 += distance[i];
else
sum2 += distance[i];
}
return sum1 < sum2 ? sum1 : sum2;
}

38
leetcode/src/1189.c Normal file
View File

@ -0,0 +1,38 @@
int maxNumberOfBalloons(char * text){
/*
0 -> b,
1 -> a,
2 -> l,
3 -> o,
4 -> n
*/
int count_letters[5] = {0};
int i, min_counter_ballons;
for (char *ptr = text; *ptr; ptr++) {
if (*ptr == 'b') {
count_letters[0]++;
} else if(*ptr == 'a') {
count_letters[1]++;
} else if (*ptr == 'l') {
count_letters[2]++;
} else if(*ptr == 'o') {
count_letters[3]++;
} else if(*ptr == 'n') {
count_letters[4]++;
}
}
/* Divide by 2 the repeted letters */
count_letters[2] /= 2;
count_letters[3] /= 2;
/* Max number of times which we can write ballon is equal to min value of letters on count_letter */
min_counter_ballons = count_letters[0];
for (i = 1; i < 5; i++) {
if (count_letters[i] < min_counter_ballons)
min_counter_ballons = count_letters[i];
}
return min_counter_ballons;
}

164
leetcode/src/12.c Normal file
View File

@ -0,0 +1,164 @@
char *getOne(char c){
switch (c) {
case '9':
return "IX";
case '8':
return "VIII";
case '7':
return "VII";
case '6':
return "VI";
case '5':
return "V";
case '4':
return "IV";
case '3':
return "III";
case '2':
return "II";
case '1':
return "I";
case '0':
return "";
default:
return NULL;
}
}
char *getTen(char c){
switch (c) {
case '9':
return "XC";
case '8':
return "LXXX";
case '7':
return "LXX";
case '6':
return "LX";
case '5':
return "L";
case '4':
return "XL";
case '3':
return "XXX";
case '2':
return "XX";
case '1':
return "X";
case '0':
return "";
default:
return NULL;
}
}
char *getHundred(char c){
switch (c) {
case '9':
return "CM";
case '8':
return "DCCC";
case '7':
return "DCC";
case '6':
return "DC";
case '5':
return "D";
case '4':
return "CD";
case '3':
return "CCC";
case '2':
return "CC";
case '1':
return "C";
case '0':
return "";
default:
return NULL;
}
}
char *getThousand(char c){
switch (c) {
case '3':
return "MMM";
case '2':
return "MM";
case '1':
return "M";
default:
return NULL;
}
}
char * intToRoman(int num){
int length;
char number[5];
char *s = malloc(16*sizeof(char));
sprintf(number, "%i", num);
length = strlen(number);
switch (length){
case 4:
sprintf(s,"%s%s%s%s", getThousand(number[0]), getHundred(number[1]), getTen(number[2]), getOne(number[3]));
break;
case 3:
sprintf(s,"%s%s%s", getHundred(number[0]), getTen(number[1]), getOne(number[2]));
break;
case 2:
sprintf(s,"%s%s", getTen(number[0]), getOne(number[1]));
break;
case 1:
s = getOne(number[0]);
break;
default:
break;
}
return s;
}

25
leetcode/src/1207.c Normal file
View File

@ -0,0 +1,25 @@
#define MAP_SIZE 2048
int cmpvalue(const void *a, const void *b) {
return *(int *)b - *(int *)a;
}
bool uniqueOccurrences(int* arr, int arrSize){
int *map = calloc(MAP_SIZE, sizeof(int));
int i;
for(i = 0; i < arrSize; i++) {
if (arr[i] < 0)
map[arr[i] + MAP_SIZE/2] += 1;
else
map[arr[i]] += 1;
}
/* number of occurrences is sorted by decreasing order
Ex: 3 2 1 0 0 0 0 */
qsort(map, MAP_SIZE, sizeof(int), cmpvalue);
i = 0;
while(map[i]) {
if(map[i] == map[i+1])
return 0;
i++;
}
return 1;
}

17
leetcode/src/121.c Normal file
View File

@ -0,0 +1,17 @@
int maxcmp(int a, int b) {
return (a >= b)? a : b;
}
/* max subarray problem by using Kadane's Algorithm
*/
int maxProfit(int* prices, int pricesSize){
/* maxCur: current maximum
* maxSoFar: found maximum for subarray so far
*/
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < pricesSize; i++) {
maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]);
maxSoFar = maxcmp(maxSoFar, maxCur);
}
return maxSoFar;
}

19
leetcode/src/125.c Normal file
View File

@ -0,0 +1,19 @@
bool isPalindrome(char * s){
int start = 0, end = strlen(s) - 1;
while(start < end) {
if (!isalpha(s[start]) && !isalnum(s[start])) {
start++;
}
else if (!isalpha(s[end]) && !isalnum(s[end])) {
end--;
} else {
char c1 = tolower(s[start]);
char c2 = tolower(s[end]);
if(c1 != c2)
return 0;
start++;
end--;
}
}
return 1;
}

49
leetcode/src/13.c Normal file
View File

@ -0,0 +1,49 @@
int romanToInt(char * s){
int romanToInt = 0;
for (int i = 0; i < strlen(s); i++) {
switch(s[i]) {
case 'I':
if (i+1 < strlen(s)) {
if (s[i + 1] == 'V' || s[i + 1] == 'X') {
romanToInt -= 1;
break;
}
}
romanToInt += 1;
break;
case 'V':
romanToInt += 5;
break;
case 'X':
if (i+1 < strlen(s)) {
if (s[i + 1] == 'L' || s[i + 1] == 'C') {
romanToInt -= 10;
break;
}
}
romanToInt += 10;
break;
case 'L':
romanToInt += 50;
break;
case 'C':
if (i+1 < strlen(s)) {
if (s[i + 1] == 'D' || s[i + 1] == 'M') {
romanToInt -= 100;
break;
}
}
romanToInt += 100;
break;
case 'D':
romanToInt += 500;
break;
case 'M':
romanToInt += 1000;
break;
default:
break;
}
}
return romanToInt;
}

6
leetcode/src/136.c Normal file
View File

@ -0,0 +1,6 @@
int singleNumber(int* nums, int numsSize){
int i, result = 0;
for(i = 0; i < numsSize; i++)
result = result ^ nums[i];
return result;
}

16
leetcode/src/141.c Normal file
View File

@ -0,0 +1,16 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *fast=head, *slow=head;
while( slow && fast && fast->next ){
fast=fast->next->next;
slow=slow->next;
if(fast==slow) return true;
}
return false;
}

19
leetcode/src/142.c Normal file
View File

@ -0,0 +1,19 @@
struct ListNode *detectCycle(struct ListNode *head) {
if (head == NULL || head->next == NULL)
return NULL;
struct ListNode *slow, *fast;
slow = fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
struct ListNode *entry = head;
while(slow != entry) {
slow = slow -> next;
entry = entry -> next;
}
return entry;
}
}
return NULL;
}

13
leetcode/src/153.c Normal file
View File

@ -0,0 +1,13 @@
int findMin(int* nums, int numsSize){
int low = 0, high = numsSize - 1;
while (low < high) {
int mid = low + (high - low) / 2;
/* minimum is on left side */
if (nums[mid] < nums[high])
high = mid;
/* minimum is on right side */
else
low = mid + 1;
}
return nums[low];
}

Some files were not shown because too many files have changed in this diff Show More