mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-21 21:11:57 +03:00
formatting source-code for b388e4a309
This commit is contained in:
parent
b388e4a309
commit
0779a2b70d
@ -1,25 +1,27 @@
|
||||
// Client side implementation of UDP client-server model
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define PORT 8080
|
||||
#define MAXLINE 1024
|
||||
|
||||
// Driver code
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
int sockfd;
|
||||
char buffer[MAXLINE];
|
||||
char *hello = "Hello from client";
|
||||
struct sockaddr_in servaddr;
|
||||
|
||||
// Creating socket file descriptor
|
||||
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
|
||||
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
|
||||
{
|
||||
perror("socket creation failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
@ -33,14 +35,12 @@ int main() {
|
||||
|
||||
int n, len;
|
||||
|
||||
sendto(sockfd, (const char *)hello, strlen(hello),
|
||||
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
|
||||
sizeof(servaddr));
|
||||
sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM,
|
||||
(const struct sockaddr *)&servaddr, sizeof(servaddr));
|
||||
printf("Hello message sent.\n");
|
||||
|
||||
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
|
||||
MSG_WAITALL, (struct sockaddr *) &servaddr,
|
||||
&len);
|
||||
n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL,
|
||||
(struct sockaddr *)&servaddr, &len);
|
||||
buffer[n] = '\0';
|
||||
printf("Server : %s\n", buffer);
|
||||
|
||||
|
@ -1,25 +1,27 @@
|
||||
// Server side implementation of UDP client-server model
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define PORT 8080
|
||||
#define MAXLINE 1024
|
||||
|
||||
// Driver code
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
int sockfd;
|
||||
char buffer[MAXLINE];
|
||||
char *hello = "Hello from server";
|
||||
struct sockaddr_in servaddr, cliaddr;
|
||||
|
||||
// Creating socket file descriptor
|
||||
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
|
||||
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
|
||||
{
|
||||
perror("socket creation failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
@ -33,22 +35,19 @@ int main() {
|
||||
servaddr.sin_port = htons(PORT);
|
||||
|
||||
// Bind the socket with the server address
|
||||
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
|
||||
sizeof(servaddr)) < 0 )
|
||||
if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
|
||||
{
|
||||
perror("bind failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
int len, n;
|
||||
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
|
||||
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
|
||||
&len);
|
||||
n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL,
|
||||
(struct sockaddr *)&cliaddr, &len);
|
||||
buffer[n] = '\0';
|
||||
printf("Client : %s\n", buffer);
|
||||
sendto(sockfd, (const char *)hello, strlen(hello),
|
||||
MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
|
||||
len);
|
||||
sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM,
|
||||
(const struct sockaddr *)&cliaddr, len);
|
||||
printf("Hello message sent.\n");
|
||||
|
||||
return 0;
|
||||
|
@ -1,11 +1,11 @@
|
||||
// Write CPP code here
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <unistd.h>
|
||||
#define MAX 80
|
||||
#define PORT 8080
|
||||
#define SA struct sockaddr
|
||||
|
@ -1,11 +1,11 @@
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#define MAX 80
|
||||
#define PORT 8080
|
||||
#define SA struct sockaddr
|
||||
@ -16,7 +16,8 @@ void func(int sockfd)
|
||||
char buff[MAX];
|
||||
int n;
|
||||
// infinite loop for chat
|
||||
for (;;) {
|
||||
for (;;)
|
||||
{
|
||||
bzero(buff, MAX);
|
||||
|
||||
// read the message from client and copy it in buffer
|
||||
@ -33,7 +34,8 @@ void func(int sockfd)
|
||||
write(sockfd, buff, sizeof(buff));
|
||||
|
||||
// if msg contains "Exit" then server exit and chat ended.
|
||||
if (strncmp("exit", buff, 4) == 0) {
|
||||
if (strncmp("exit", buff, 4) == 0)
|
||||
{
|
||||
printf("Server Exit...\n");
|
||||
break;
|
||||
}
|
||||
@ -48,7 +50,8 @@ int main()
|
||||
|
||||
// socket create and verification
|
||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1) {
|
||||
if (sockfd == -1)
|
||||
{
|
||||
printf("socket creation failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
@ -62,7 +65,8 @@ int main()
|
||||
servaddr.sin_port = htons(PORT);
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
|
||||
if ((bind(sockfd, (SA *)&servaddr, sizeof(servaddr))) != 0)
|
||||
{
|
||||
printf("socket bind failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
@ -70,7 +74,8 @@ int main()
|
||||
printf("Socket successfully binded..\n");
|
||||
|
||||
// Now server is ready to listen and verification
|
||||
if ((listen(sockfd, 5)) != 0) {
|
||||
if ((listen(sockfd, 5)) != 0)
|
||||
{
|
||||
printf("Listen failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
@ -80,7 +85,8 @@ int main()
|
||||
|
||||
// Accept the data packet from client and verification
|
||||
connfd = accept(sockfd, (SA *)&cli, &len);
|
||||
if (connfd < 0) {
|
||||
if (connfd < 0)
|
||||
{
|
||||
printf("server acccept failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
|
@ -5,20 +5,21 @@
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
|
||||
int remainder, number = 0, decimal_number = 0, temp = 1;
|
||||
printf("/n Enter any binary number= ");
|
||||
scanf("%d", &number);
|
||||
|
||||
// Iterate over the number until the end.
|
||||
while(number > 0) {
|
||||
while (number > 0)
|
||||
{
|
||||
|
||||
remainder = number % 10;
|
||||
number = number / 10;
|
||||
decimal_number += remainder * temp;
|
||||
temp = temp * 2; // used as power of 2
|
||||
|
||||
}
|
||||
|
||||
printf("%d\n", decimal_number);
|
||||
|
@ -25,10 +25,12 @@ int main(void)
|
||||
|
||||
while (binary_num > 0)
|
||||
{
|
||||
if(binary_num > 111) //Checking if binary number is greater than three digits
|
||||
if (binary_num >
|
||||
111) // Checking if binary number is greater than three digits
|
||||
td = three_digits(binary_num);
|
||||
|
||||
else td = binary_num;
|
||||
else
|
||||
td = binary_num;
|
||||
|
||||
binary_num /= 1000;
|
||||
|
||||
|
@ -44,7 +44,6 @@ int main()
|
||||
|
||||
bits[i] = re;
|
||||
i++;
|
||||
|
||||
}
|
||||
|
||||
printf("\n the number in binary is: ");
|
||||
@ -63,4 +62,3 @@ int main()
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
@ -2,8 +2,8 @@
|
||||
#include <stdio.h>
|
||||
void decimal2Hexadecimal(long num);
|
||||
|
||||
|
||||
int main(){
|
||||
int main()
|
||||
{
|
||||
|
||||
long decimalnum;
|
||||
|
||||
@ -15,8 +15,10 @@ int main(){
|
||||
return 0;
|
||||
}
|
||||
|
||||
/********function for convert decimal number to hexadecimal number****************/
|
||||
void decimal2Hexadecimal(long num){
|
||||
/********function for convert decimal number to hexadecimal
|
||||
* number****************/
|
||||
void decimal2Hexadecimal(long num)
|
||||
{
|
||||
|
||||
long decimalnum = num;
|
||||
long quotient, remainder;
|
||||
@ -25,7 +27,8 @@ char hexadecimalnum[100];
|
||||
|
||||
quotient = decimalnum;
|
||||
|
||||
while (quotient != 0){
|
||||
while (quotient != 0)
|
||||
{
|
||||
|
||||
remainder = quotient % 16;
|
||||
if (remainder < 10)
|
||||
@ -34,13 +37,15 @@ char hexadecimalnum[100];
|
||||
else
|
||||
hexadecimalnum[j++] = 55 + remainder;
|
||||
|
||||
quotient = quotient / 16;}
|
||||
quotient = quotient / 16;
|
||||
}
|
||||
|
||||
// print the hexadecimal number
|
||||
|
||||
for (i = j; i >= 0; i--){
|
||||
printf("%c", hexadecimalnum[i]);}
|
||||
for (i = j; i >= 0; i--)
|
||||
{
|
||||
printf("%c", hexadecimalnum[i]);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,8 @@
|
||||
#include <stdio.h>
|
||||
void decimal2Octal(long decimalnum);
|
||||
|
||||
int main(){
|
||||
int main()
|
||||
{
|
||||
|
||||
long decimalnum;
|
||||
|
||||
@ -15,13 +16,15 @@ return 0;
|
||||
}
|
||||
|
||||
/********function for convert decimal numbers to octal numbers************/
|
||||
void decimal2Octal(long decimalnum){
|
||||
void decimal2Octal(long decimalnum)
|
||||
{
|
||||
long remainder, quotient;
|
||||
|
||||
int octalNumber[100], i = 1, j;
|
||||
quotient = decimalnum;
|
||||
|
||||
while (quotient != 0){
|
||||
while (quotient != 0)
|
||||
{
|
||||
octalNumber[i++] = quotient % 8;
|
||||
|
||||
quotient = quotient / 8;
|
||||
|
@ -2,15 +2,15 @@
|
||||
#include <stdio.h>
|
||||
|
||||
// Converts octal number to decimal
|
||||
int convertValue(int num, int i) {
|
||||
return num * pow(8, i);
|
||||
}
|
||||
int convertValue(int num, int i) { return num * pow(8, i); }
|
||||
|
||||
long long toDecimal(int octal_value) {
|
||||
long long toDecimal(int octal_value)
|
||||
{
|
||||
|
||||
int decimal_value = 0, i = 0;
|
||||
|
||||
while (octal_value) {
|
||||
while (octal_value)
|
||||
{
|
||||
|
||||
// Extracts right-most digit and then multiplies by 8^i
|
||||
decimal_value += convertValue(octal_value % 10, i++);
|
||||
@ -22,7 +22,8 @@ long long toDecimal(int octal_value) {
|
||||
return decimal_value;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
|
||||
printf("Enter octal value: ");
|
||||
|
||||
|
@ -2,10 +2,11 @@
|
||||
* convert from any base to decimal
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
int main(void)
|
||||
{
|
||||
int base, i, j;
|
||||
char number[100];
|
||||
unsigned long decimal = 0;
|
||||
@ -15,7 +16,8 @@ int main(void) {
|
||||
printf("Enter the number: ");
|
||||
scanf("%s", &number[0]);
|
||||
|
||||
for (i = 0; number[i] != '\0'; i++) {
|
||||
for (i = 0; number[i] != '\0'; i++)
|
||||
{
|
||||
if (isdigit(number[i]))
|
||||
number[i] -= '0';
|
||||
else if (isupper(number[i]))
|
||||
@ -25,13 +27,15 @@ 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++) {
|
||||
for (j = 0; j < i; j++)
|
||||
{
|
||||
decimal *= base;
|
||||
decimal += number[j];
|
||||
}
|
||||
|
@ -26,10 +26,10 @@
|
||||
|
||||
*/
|
||||
|
||||
#include "CArray.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include "CArray.h"
|
||||
|
||||
void swap(CArray *array, int position1, int position2);
|
||||
|
||||
@ -39,7 +39,8 @@ CArray * getCArray(int size)
|
||||
array->array = (int *)malloc(sizeof(int) * size);
|
||||
array->size = size;
|
||||
int i;
|
||||
for (i = 0; i < size; i++) {
|
||||
for (i = 0; i < size; i++)
|
||||
{
|
||||
array->array[i] = 0;
|
||||
}
|
||||
return array;
|
||||
@ -47,23 +48,29 @@ CArray * getCArray(int size)
|
||||
|
||||
int insertValueCArray(CArray *array, int position, int value)
|
||||
{
|
||||
if (position >= 0 && position < array->size) {
|
||||
if (array->array[position] == 0) {
|
||||
if (position >= 0 && position < array->size)
|
||||
{
|
||||
if (array->array[position] == 0)
|
||||
{
|
||||
array->array[position] = value;
|
||||
return SUCCESS;
|
||||
}
|
||||
else return POSITION_INIT;
|
||||
else
|
||||
return POSITION_INIT;
|
||||
}
|
||||
return INVALID_POSITION;
|
||||
}
|
||||
|
||||
int removeValueCArray(CArray *array, int position)
|
||||
{
|
||||
if (position >= 0 && position < array->size) {
|
||||
if (array->array[position] != 0) {
|
||||
if (position >= 0 && position < array->size)
|
||||
{
|
||||
if (array->array[position] != 0)
|
||||
{
|
||||
array->array[position] = 0;
|
||||
}
|
||||
else return POSITION_EMPTY;
|
||||
else
|
||||
return POSITION_EMPTY;
|
||||
}
|
||||
return INVALID_POSITION;
|
||||
}
|
||||
@ -72,25 +79,31 @@ int pushValueCArray(CArray *array, int value)
|
||||
{
|
||||
int i;
|
||||
int ok = 0;
|
||||
for (i = 0; i < array->size; i++) {
|
||||
if (array->array[i] == 0) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
if (array->array[i] == 0)
|
||||
{
|
||||
array->array[i] = value;
|
||||
ok = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok == 1) return SUCCESS;
|
||||
else return ARRAY_FULL;
|
||||
if (ok == 1)
|
||||
return SUCCESS;
|
||||
else
|
||||
return ARRAY_FULL;
|
||||
}
|
||||
|
||||
int updateValueCArray(CArray *array, int position, int value)
|
||||
{
|
||||
if (position >= 0 && position < array->size) {
|
||||
if (array->array[position] != 0) {
|
||||
|
||||
if (position >= 0 && position < array->size)
|
||||
{
|
||||
if (array->array[position] != 0)
|
||||
{
|
||||
}
|
||||
|
||||
else return POSITION_NOT_INIT;
|
||||
else
|
||||
return POSITION_NOT_INIT;
|
||||
}
|
||||
return INVALID_POSITION;
|
||||
}
|
||||
@ -98,7 +111,8 @@ int updateValueCArray(CArray *array, int position, int value)
|
||||
int eraseCArray(CArray *array)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < array->size; i++) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
array->array[i] = 0;
|
||||
}
|
||||
return 0;
|
||||
@ -106,8 +120,9 @@ int eraseCArray(CArray *array)
|
||||
|
||||
int switchValuesCArray(CArray *array, int position1, int position2)
|
||||
{
|
||||
if (position1 >= 0 && position1 < array->size
|
||||
&& position2 >= 0 && position2 < array->size) {
|
||||
if (position1 >= 0 && position1 < array->size && position2 >= 0 &&
|
||||
position2 < array->size)
|
||||
{
|
||||
int temp = array->array[position1];
|
||||
array->array[position1] = array->array[position2];
|
||||
array->array[position2] = temp;
|
||||
@ -118,7 +133,8 @@ int switchValuesCArray(CArray *array, int position1, int position2)
|
||||
int reverseCArray(CArray *array)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < array->size / 2; i++) {
|
||||
for (i = 0; i < array->size / 2; i++)
|
||||
{
|
||||
swap(array, i, array->size - i - 1);
|
||||
}
|
||||
return SUCCESS;
|
||||
@ -128,7 +144,8 @@ int displayCArray(CArray *array)
|
||||
{
|
||||
int i;
|
||||
printf("\nC ARRAY\n");
|
||||
for (i = 0; i < array->size; i++) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
printf("%d ", array->array[i]);
|
||||
}
|
||||
printf("\n");
|
||||
@ -140,7 +157,8 @@ int blenderCArray(CArray *array)
|
||||
srand(time(NULL) * array->size);
|
||||
int i;
|
||||
int total = array->size * 100;
|
||||
for (i = 0; i < total; i++) {
|
||||
for (i = 0; i < total; i++)
|
||||
{
|
||||
swap(array, rand() % array->size, rand() % array->size);
|
||||
}
|
||||
return 0;
|
||||
@ -152,7 +170,8 @@ CArray * getCopyCArray(CArray *arr)
|
||||
array->array = (int *)malloc(sizeof(int) * arr->size);
|
||||
array->size = arr->size;
|
||||
int i;
|
||||
for (i = 0; i < arr->size; i++) {
|
||||
for (i = 0; i < arr->size; i++)
|
||||
{
|
||||
array->array[i] = arr->array[i];
|
||||
}
|
||||
return array;
|
||||
@ -168,9 +187,12 @@ void swap(CArray *array, int position1, int position2)
|
||||
int bubbleSortCArray(CArray *array)
|
||||
{
|
||||
int i, j;
|
||||
for (i = 0; i < array->size - 1; i++) {
|
||||
for (j = 0; j < array->size - i - 1; j++) {
|
||||
if (array->array[j] > array->array[j + 1]) {
|
||||
for (i = 0; i < array->size - 1; i++)
|
||||
{
|
||||
for (j = 0; j < array->size - i - 1; j++)
|
||||
{
|
||||
if (array->array[j] > array->array[j + 1])
|
||||
{
|
||||
swap(array, j, j + 1);
|
||||
}
|
||||
}
|
||||
@ -181,10 +203,12 @@ int bubbleSortCArray(CArray *array)
|
||||
int selectionSortCArray(CArray *array)
|
||||
{
|
||||
int i, j, min;
|
||||
for (i = 0; i < array->size - 1; i++) {
|
||||
for (i = 0; i < array->size - 1; i++)
|
||||
{
|
||||
min = i;
|
||||
for (j = i + 1; j < array->size; j++)
|
||||
if (array->array[j] < array->array[min]) min = j;
|
||||
if (array->array[j] < array->array[min])
|
||||
min = j;
|
||||
swap(array, min, i);
|
||||
}
|
||||
return 0;
|
||||
@ -193,7 +217,8 @@ int selectionSortCArray(CArray *array)
|
||||
int insertionSortCArray(CArray *array)
|
||||
{
|
||||
int i, j, num;
|
||||
for (i = 1; i < array->size; i++) {
|
||||
for (i = 1; i < array->size; i++)
|
||||
{
|
||||
num = array->array[i];
|
||||
j = i - 1;
|
||||
while (j >= 0 && array->array[j] > num)
|
||||
@ -209,8 +234,10 @@ int insertionSortCArray(CArray *array)
|
||||
int valueOcurranceCArray(CArray *array, int value)
|
||||
{
|
||||
int i, total = 0;
|
||||
for (i = 0; i < array->size; i++) {
|
||||
if (array->array[i] == value) total++;
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
if (array->array[i] == value)
|
||||
total++;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
@ -220,8 +247,10 @@ CArray * valuePositionsCArray(CArray *array, int value)
|
||||
int i, j = 0;
|
||||
int total = valueOcurranceCArray(array, value);
|
||||
CArray *resultArray = getCArray(total);
|
||||
for (i = 0; i < array->size; i++) {
|
||||
if (array->array[i] == value) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
if (array->array[i] == value)
|
||||
{
|
||||
// Hopefully this won't overflow
|
||||
resultArray->array[j] = i;
|
||||
j++;
|
||||
@ -234,8 +263,10 @@ int findMinCArray(CArray *array)
|
||||
{
|
||||
int i;
|
||||
int min = array->array[0];
|
||||
for (i = 1; i < array->size; i++) {
|
||||
if (array->array[i] < min) {
|
||||
for (i = 1; i < array->size; i++)
|
||||
{
|
||||
if (array->array[i] < min)
|
||||
{
|
||||
min = array->array[i];
|
||||
}
|
||||
}
|
||||
@ -246,8 +277,10 @@ int findMaxCArray(CArray *array)
|
||||
{
|
||||
int i;
|
||||
int max = array->array[0];
|
||||
for (i = 1; i < array->size; i++) {
|
||||
if (array->array[i] > max) {
|
||||
for (i = 1; i < array->size; i++)
|
||||
{
|
||||
if (array->array[i] > max)
|
||||
{
|
||||
max = array->array[i];
|
||||
}
|
||||
}
|
||||
|
@ -16,7 +16,8 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#define ARRAY_ERASED -1
|
||||
@ -27,7 +28,8 @@ extern "C" {
|
||||
#define POSITION_EMPTY 4
|
||||
#define ARRAY_FULL 5
|
||||
|
||||
typedef struct CArray {
|
||||
typedef struct CArray
|
||||
{
|
||||
int *array;
|
||||
int size;
|
||||
} CArray;
|
||||
@ -78,7 +80,6 @@ extern "C" {
|
||||
// +-------------------------------------+
|
||||
int displayCArray(CArray *array);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
@ -13,10 +13,10 @@
|
||||
*
|
||||
*/
|
||||
|
||||
#include "CArray.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include "CArray.h"
|
||||
|
||||
int CArrayTests()
|
||||
{
|
||||
@ -31,14 +31,16 @@ int CArrayTests()
|
||||
CArray *array = getCArray(10);
|
||||
|
||||
int i;
|
||||
for (i = 0; i < array->size; i++) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
insertValueCArray(array, i, i + 1);
|
||||
}
|
||||
printf("Entered array is:\n");
|
||||
displayCArray(array);
|
||||
printf("\nCode: %d\n", pushValueCArray(array, 11)); // 5
|
||||
|
||||
for (i = 0; i < array->size; i++) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
removeValueCArray(array, i);
|
||||
}
|
||||
|
||||
@ -48,7 +50,8 @@ int CArrayTests()
|
||||
printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1
|
||||
|
||||
// Erase
|
||||
for (i = 0; i < array->size; i++) {
|
||||
for (i = 0; i < array->size; i++)
|
||||
{
|
||||
insertValueCArray(array, i, i + 1);
|
||||
}
|
||||
eraseCArray(array);
|
||||
@ -56,11 +59,13 @@ int CArrayTests()
|
||||
|
||||
// Switching
|
||||
CArray *arr = getCArray(13);
|
||||
for (i = 0; i < arr->size; i++) {
|
||||
for (i = 0; i < arr->size; i++)
|
||||
{
|
||||
insertValueCArray(arr, i, i + 1);
|
||||
}
|
||||
displayCArray(arr);
|
||||
for (i = 0; i < arr->size / 2; i++) {
|
||||
for (i = 0; i < arr->size / 2; i++)
|
||||
{
|
||||
switchValuesCArray(arr, i, arr->size - i - 1);
|
||||
}
|
||||
|
||||
@ -74,7 +79,8 @@ int CArrayTests()
|
||||
// Sorting
|
||||
srand(time(NULL));
|
||||
CArray *barray = getCArray(20);
|
||||
for (i = 0; i < barray->size; i++) {
|
||||
for (i = 0; i < barray->size; i++)
|
||||
{
|
||||
insertValueCArray(barray, i, rand());
|
||||
}
|
||||
CArray *carray = getCopyCArray(barray);
|
||||
@ -120,7 +126,8 @@ int CArrayTests()
|
||||
|
||||
// Searching
|
||||
CArray *aarray = getCArray(1000);
|
||||
for (i = 0; i < aarray->size; i++) {
|
||||
for (i = 0; i < aarray->size; i++)
|
||||
{
|
||||
insertValueCArray(aarray, i, rand() % 100);
|
||||
}
|
||||
|
||||
@ -132,9 +139,10 @@ int CArrayTests()
|
||||
displayCArray(positions);
|
||||
// This should all give value of j
|
||||
printf("\nAll %d s", j);
|
||||
for (i = 0; i < positions->size; i++) {
|
||||
printf("\nPosition %d has a value of %d",
|
||||
positions->array[i], aarray->array[positions->array[i]]);
|
||||
for (i = 0; i < positions->size; i++)
|
||||
{
|
||||
printf("\nPosition %d has a value of %d", positions->array[i],
|
||||
aarray->array[positions->array[i]]);
|
||||
}
|
||||
printf("\nThe list has a minimum value of %d and a maximum value of %d",
|
||||
findMinCArray(aarray), findMaxCArray(aarray));
|
||||
|
@ -10,10 +10,7 @@ struct AVLnode
|
||||
};
|
||||
typedef struct AVLnode avlNode;
|
||||
|
||||
int max(int a, int b)
|
||||
{
|
||||
return (a > b)? a : b;
|
||||
}
|
||||
int max(int a, int b) { return (a > b) ? a : b; }
|
||||
|
||||
avlNode *newNode(int key)
|
||||
{
|
||||
@ -127,14 +124,15 @@ avlNode *insert(avlNode *node, int key)
|
||||
/*Binary Search Tree insertion*/
|
||||
|
||||
if (key < node->key)
|
||||
node->left = insert(node->left, key); /*Recursive insertion in L subtree*/
|
||||
node->left =
|
||||
insert(node->left, key); /*Recursive insertion in L subtree*/
|
||||
else if (key > node->key)
|
||||
node->right = insert(node->right, key); /*Recursive insertion in R subtree*/
|
||||
node->right =
|
||||
insert(node->right, key); /*Recursive insertion in R subtree*/
|
||||
|
||||
/* Node Height as per the AVL formula*/
|
||||
node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1);
|
||||
|
||||
|
||||
/*Checking for the balance condition*/
|
||||
int balance = heightDiff(node);
|
||||
|
||||
@ -159,7 +157,6 @@ avlNode *insert(avlNode *node, int key)
|
||||
}
|
||||
|
||||
return node;
|
||||
|
||||
}
|
||||
|
||||
avlNode *delete (avlNode *node, int queryNum)
|
||||
@ -168,17 +165,17 @@ avlNode *delete(avlNode *node, int queryNum)
|
||||
return node;
|
||||
|
||||
if (queryNum < node->key)
|
||||
node->left = delete(node->left, queryNum); /*Recursive deletion in L subtree*/
|
||||
node->left =
|
||||
delete (node->left, queryNum); /*Recursive deletion in L subtree*/
|
||||
else if (queryNum > node->key)
|
||||
node->right = delete(node->right, queryNum); /*Recursive deletion in R subtree*/
|
||||
node->right =
|
||||
delete (node->right, queryNum); /*Recursive deletion in R subtree*/
|
||||
else
|
||||
{
|
||||
/*Single or No Child*/
|
||||
if ((node->left == NULL) || (node->right == NULL))
|
||||
{
|
||||
avlNode *temp = node->left ?
|
||||
node->left :
|
||||
node->right;
|
||||
avlNode *temp = node->left ? node->left : node->right;
|
||||
|
||||
/* No Child*/
|
||||
if (temp == NULL)
|
||||
@ -198,7 +195,9 @@ avlNode *delete(avlNode *node, int queryNum)
|
||||
/*Get the smallest key in the R subtree*/
|
||||
avlNode *temp = minNode(node->right);
|
||||
node->key = temp->key; /*Copy that to the root*/
|
||||
node->right = delete(node->right, temp->key); /*Delete the smallest in the R subtree.*/
|
||||
node->right =
|
||||
delete (node->right,
|
||||
temp->key); /*Delete the smallest in the R subtree.*/
|
||||
}
|
||||
}
|
||||
|
||||
@ -206,7 +205,6 @@ avlNode *delete(avlNode *node, int queryNum)
|
||||
if (node == NULL)
|
||||
return node;
|
||||
|
||||
|
||||
/*Update height*/
|
||||
node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1);
|
||||
|
||||
@ -233,7 +231,6 @@ avlNode *delete(avlNode *node, int queryNum)
|
||||
}
|
||||
|
||||
return node;
|
||||
|
||||
}
|
||||
|
||||
avlNode *findNode(avlNode *node, int queryNum)
|
||||
@ -367,12 +364,12 @@ int main()
|
||||
|
||||
tempNode = findNode(root, queryNum);
|
||||
|
||||
|
||||
if (tempNode == NULL)
|
||||
printf("\n\t %d : Not Found\n", queryNum);
|
||||
else
|
||||
{
|
||||
printf("\n\t %d : Found at height %d \n", queryNum, tempNode->height);
|
||||
printf("\n\t %d : Found at height %d \n", queryNum,
|
||||
tempNode->height);
|
||||
|
||||
printf("\n\tPrinting AVL Tree\n");
|
||||
printAVL(root, 1);
|
||||
@ -420,12 +417,8 @@ int main()
|
||||
printf("\n\t\tExiting, Thank You !!\n");
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
@ -1,7 +1,8 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
/* A basic unbalanced binary search tree implementation in C, with the following functionalities implemented:
|
||||
/* A basic unbalanced binary search tree implementation in C, with the following
|
||||
functionalities implemented:
|
||||
- Insertion
|
||||
- Deletion
|
||||
- Search by key value
|
||||
@ -9,7 +10,8 @@
|
||||
*/
|
||||
|
||||
// Node, the basic data structure in the tree
|
||||
typedef struct node{
|
||||
typedef struct node
|
||||
{
|
||||
|
||||
// left child
|
||||
struct node *left;
|
||||
@ -21,8 +23,10 @@ typedef struct node{
|
||||
int data;
|
||||
} node;
|
||||
|
||||
// The node constructor, which receives the key value input and returns a node pointer
|
||||
node* newNode(int data){
|
||||
// The node constructor, which receives the key value input and returns a node
|
||||
// pointer
|
||||
node *newNode(int data)
|
||||
{
|
||||
|
||||
// creates a slug
|
||||
node *tmp = (node *)malloc(sizeof(node));
|
||||
@ -36,14 +40,17 @@ node* newNode(int data){
|
||||
}
|
||||
|
||||
// Insertion procedure, which inserts the input key in a new node in the tree
|
||||
node* insert(node* root, int data){
|
||||
node *insert(node *root, int data)
|
||||
{
|
||||
// If the root of the subtree is null, insert key here
|
||||
if (root == NULL)
|
||||
root = newNode(data);
|
||||
// If it isn't null and the input key is greater than the root key, insert in the right leaf
|
||||
// If it isn't null and the input key is greater than the root key, insert
|
||||
// in the right leaf
|
||||
else if (data > root->data)
|
||||
root->right = insert(root->right, data);
|
||||
// If it isn't null and the input key is lower than the root key, insert in the left leaf
|
||||
// If it isn't null and the input key is lower than the root key, insert in
|
||||
// the left leaf
|
||||
else if (data < root->data)
|
||||
root->left = insert(root->left, data);
|
||||
// Returns the modified tree
|
||||
@ -51,7 +58,8 @@ node* insert(node* root, int data){
|
||||
}
|
||||
|
||||
// Utilitary procedure to find the greatest key in the left subtree
|
||||
node* getMax(node* root){
|
||||
node *getMax(node *root)
|
||||
{
|
||||
// If there's no leaf to the right, then this is the maximum key value
|
||||
if (root->right == NULL)
|
||||
return root;
|
||||
@ -59,8 +67,10 @@ node* getMax(node* root){
|
||||
root->right = getMax(root->right);
|
||||
}
|
||||
|
||||
// Deletion procedure, which searches for the input key in the tree and removes it if present
|
||||
node* delete(node* root, int data){
|
||||
// Deletion procedure, which searches for the input key in the tree and removes
|
||||
// it if present
|
||||
node *delete (node *root, int data)
|
||||
{
|
||||
// If the root is null, nothing to be done
|
||||
if (root == NULL)
|
||||
return root;
|
||||
@ -72,32 +82,40 @@ node* delete(node* root, int data){
|
||||
root->left = delete (root->left, data);
|
||||
// If the input key matches the root's, check the following cases
|
||||
// termination condition
|
||||
else if (data == root->data){
|
||||
else if (data == root->data)
|
||||
{
|
||||
// Case 1: the root has no leaves, remove the node
|
||||
if ((root->left == NULL) && (root->right == NULL)){
|
||||
if ((root->left == NULL) && (root->right == NULL))
|
||||
{
|
||||
free(root);
|
||||
return NULL;
|
||||
}
|
||||
// Case 2: the root has one leaf, make the leaf the new root and remove the old root
|
||||
else if (root->left == NULL){
|
||||
// Case 2: the root has one leaf, make the leaf the new root and remove
|
||||
// the old root
|
||||
else if (root->left == NULL)
|
||||
{
|
||||
node *tmp = root;
|
||||
root = root->right;
|
||||
free(tmp);
|
||||
return root;
|
||||
}
|
||||
else if (root->right == NULL){
|
||||
else if (root->right == NULL)
|
||||
{
|
||||
node *tmp = root;
|
||||
root = root->left;
|
||||
free(tmp);
|
||||
return root;
|
||||
}
|
||||
// Case 3: the root has 2 leaves, find the greatest key in the left subtree and switch with the root's
|
||||
else {
|
||||
// Case 3: the root has 2 leaves, find the greatest key in the left
|
||||
// subtree and switch with the root's
|
||||
else
|
||||
{
|
||||
|
||||
// finds the biggest node in the left branch.
|
||||
node *tmp = getMax(root->left);
|
||||
|
||||
// sets the data of this node equal to the data of the biggest node (lefts)
|
||||
// sets the data of this node equal to the data of the biggest node
|
||||
// (lefts)
|
||||
root->data = tmp->data;
|
||||
root->left = delete (root->left, tmp->data);
|
||||
}
|
||||
@ -105,8 +123,10 @@ node* delete(node* root, int data){
|
||||
return root;
|
||||
}
|
||||
|
||||
// Search procedure, which looks for the input key in the tree and returns 1 if it's present or 0 if it's not in the tree
|
||||
int find(node* root, int data){
|
||||
// Search procedure, which looks for the input key in the tree and returns 1 if
|
||||
// it's present or 0 if it's not in the tree
|
||||
int find(node *root, int data)
|
||||
{
|
||||
// If the root is null, the key's not present
|
||||
if (root == NULL)
|
||||
return 0;
|
||||
@ -122,16 +142,20 @@ int find(node* root, int data){
|
||||
}
|
||||
|
||||
// Utilitary procedure to measure the height of the binary tree
|
||||
int height(node* root){
|
||||
int height(node *root)
|
||||
{
|
||||
// If the root is null, this is the bottom of the tree (height 0)
|
||||
if (root == NULL)
|
||||
return 0;
|
||||
else{
|
||||
// Get the height from both left and right subtrees to check which is the greatest
|
||||
else
|
||||
{
|
||||
// Get the height from both left and right subtrees to check which is
|
||||
// the greatest
|
||||
int right_h = height(root->right);
|
||||
int left_h = height(root->left);
|
||||
|
||||
// The final height is the height of the greatest subtree(left or right) plus 1(which is the root's level)
|
||||
// The final height is the height of the greatest subtree(left or right)
|
||||
// plus 1(which is the root's level)
|
||||
if (right_h > left_h)
|
||||
return (right_h + 1);
|
||||
else
|
||||
@ -140,8 +164,10 @@ int height(node* root){
|
||||
}
|
||||
|
||||
// Utilitary procedure to free all nodes in a tree
|
||||
void purge(node* root){
|
||||
if (root != NULL){
|
||||
void purge(node *root)
|
||||
{
|
||||
if (root != NULL)
|
||||
{
|
||||
if (root->left != NULL)
|
||||
purge(root->left);
|
||||
if (root->right != NULL)
|
||||
@ -150,16 +176,20 @@ void purge(node* root){
|
||||
}
|
||||
}
|
||||
|
||||
// Traversal procedure to list the current keys in the tree in order of value (from the left to the right)
|
||||
void inOrder(node* root){
|
||||
if(root != NULL){
|
||||
// Traversal procedure to list the current keys in the tree in order of value
|
||||
// (from the left to the right)
|
||||
void inOrder(node *root)
|
||||
{
|
||||
if (root != NULL)
|
||||
{
|
||||
inOrder(root->left);
|
||||
printf("\t[ %d ]\t", root->data);
|
||||
inOrder(root->right);
|
||||
}
|
||||
}
|
||||
|
||||
void main(){
|
||||
void main()
|
||||
{
|
||||
|
||||
// this reference don't change.
|
||||
// only the tree changes.
|
||||
@ -168,19 +198,25 @@ void main(){
|
||||
int data = 0;
|
||||
|
||||
// event-loop.
|
||||
while (opt != 0){
|
||||
printf("\n\n[1] Insert Node\n[2] Delete Node\n[3] Find a Node\n[4] Get current Height\n[5] Print Tree in Crescent Order\n[0] Quit\n");
|
||||
while (opt != 0)
|
||||
{
|
||||
printf("\n\n[1] Insert Node\n[2] Delete Node\n[3] Find a Node\n[4] Get "
|
||||
"current Height\n[5] Print Tree in Crescent Order\n[0] Quit\n");
|
||||
scanf("%d", &opt); // reads the choice of the user
|
||||
|
||||
// processes the choice
|
||||
switch(opt){
|
||||
case 1: printf("Enter the new node's value:\n");
|
||||
switch (opt)
|
||||
{
|
||||
case 1:
|
||||
printf("Enter the new node's value:\n");
|
||||
scanf("%d", &data);
|
||||
root = insert(root, data);
|
||||
break;
|
||||
|
||||
case 2: printf("Enter the value to be removed:\n");
|
||||
if (root != NULL){
|
||||
case 2:
|
||||
printf("Enter the value to be removed:\n");
|
||||
if (root != NULL)
|
||||
{
|
||||
scanf("%d", &data);
|
||||
root = delete (root, data);
|
||||
}
|
||||
@ -188,15 +224,19 @@ void main(){
|
||||
printf("Tree is already empty!\n");
|
||||
break;
|
||||
|
||||
case 3: printf("Enter the searched value:\n");
|
||||
case 3:
|
||||
printf("Enter the searched value:\n");
|
||||
scanf("%d", &data);
|
||||
find(root,data) ? printf("The value is in the tree.\n") : printf("The value is not in the tree.\n");
|
||||
find(root, data) ? printf("The value is in the tree.\n")
|
||||
: printf("The value is not in the tree.\n");
|
||||
break;
|
||||
|
||||
case 4: printf("Current height of the tree is: %d\n", height(root));
|
||||
case 4:
|
||||
printf("Current height of the tree is: %d\n", height(root));
|
||||
break;
|
||||
|
||||
case 5: inOrder(root);
|
||||
case 5:
|
||||
inOrder(root);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
|
||||
typedef struct node{
|
||||
typedef struct node
|
||||
{
|
||||
int val;
|
||||
struct node *par;
|
||||
struct node *left;
|
||||
@ -11,7 +12,8 @@ typedef struct node{
|
||||
} Node;
|
||||
|
||||
// Create a new node
|
||||
Node* newNode(int val, Node* par){
|
||||
Node *newNode(int val, Node *par)
|
||||
{
|
||||
Node *create = (Node *)(malloc(sizeof(Node)));
|
||||
create->val = val;
|
||||
create->par = par;
|
||||
@ -21,30 +23,37 @@ Node* newNode(int val, Node* par){
|
||||
}
|
||||
|
||||
// Check if the node is the leaf
|
||||
int isLeaf(Node* n){
|
||||
if(n->left == NULL && n->right == NULL){
|
||||
int isLeaf(Node *n)
|
||||
{
|
||||
if (n->left == NULL && n->right == NULL)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Left Rotate
|
||||
Node* leftRotate(Node* node){
|
||||
Node *leftRotate(Node *node)
|
||||
{
|
||||
Node *parent = node->par;
|
||||
Node *grandParent = parent->par;
|
||||
|
||||
parent->right = node->left;
|
||||
if(node->left != NULL){
|
||||
if (node->left != NULL)
|
||||
{
|
||||
node->left->par = parent;
|
||||
}
|
||||
node->par = grandParent;
|
||||
parent->par = node;
|
||||
node->left = parent;
|
||||
if(grandParent != NULL){
|
||||
if(grandParent->right == parent){
|
||||
if (grandParent != NULL)
|
||||
{
|
||||
if (grandParent->right == parent)
|
||||
{
|
||||
grandParent->right = node;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
grandParent->left = node;
|
||||
}
|
||||
}
|
||||
@ -52,39 +61,46 @@ Node* leftRotate(Node* node){
|
||||
}
|
||||
|
||||
// Right Rotate
|
||||
Node* rightRotate(Node* node){
|
||||
Node *rightRotate(Node *node)
|
||||
{
|
||||
Node *parent = node->par;
|
||||
Node *grandParent = parent->par;
|
||||
|
||||
parent->left = node->right;
|
||||
if(node->right != NULL){
|
||||
if (node->right != NULL)
|
||||
{
|
||||
node->right->par = parent;
|
||||
}
|
||||
node->par = grandParent;
|
||||
parent->par = node;
|
||||
node->right = parent;
|
||||
if(grandParent != NULL){
|
||||
if(grandParent->right == parent){
|
||||
if (grandParent != NULL)
|
||||
{
|
||||
if (grandParent->right == parent)
|
||||
{
|
||||
grandParent->right = node;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
grandParent->left = node;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
// Check the node after the insertion step
|
||||
void checkNode(Node* node){
|
||||
void checkNode(Node *node)
|
||||
{
|
||||
|
||||
// If the node is the root
|
||||
if(node == NULL || node->par == NULL){
|
||||
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){
|
||||
if (node->color == 0 || (node->par)->color == 0)
|
||||
{
|
||||
// Dont Do Anything
|
||||
return;
|
||||
}
|
||||
@ -96,29 +112,35 @@ void checkNode(Node* node){
|
||||
|
||||
// If grandParent is NULL, then parent is the root.
|
||||
// Just make the root black.
|
||||
if(grandParent == NULL){
|
||||
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){
|
||||
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{
|
||||
else
|
||||
{
|
||||
// The only option left is rotation.
|
||||
Node *greatGrandParent = grandParent->par;
|
||||
// Right Case
|
||||
if(grandParent->right == parent){
|
||||
if (grandParent->right == parent)
|
||||
{
|
||||
// Right Right Case
|
||||
if(parent->right == node){
|
||||
if (parent->right == node)
|
||||
{
|
||||
grandParent->right = parent->left;
|
||||
if(parent->left != NULL){
|
||||
if (parent->left != NULL)
|
||||
{
|
||||
(parent->left)->par = grandParent;
|
||||
}
|
||||
parent->left = grandParent;
|
||||
@ -126,11 +148,15 @@ void checkNode(Node* node){
|
||||
|
||||
// Attach to existing Tree;
|
||||
parent->par = greatGrandParent;
|
||||
if(greatGrandParent != NULL){
|
||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
||||
if (greatGrandParent != NULL)
|
||||
{
|
||||
if (greatGrandParent->left != NULL &&
|
||||
greatGrandParent->left == grandParent)
|
||||
{
|
||||
greatGrandParent->left = parent;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
greatGrandParent->right = parent;
|
||||
}
|
||||
}
|
||||
@ -139,10 +165,12 @@ void checkNode(Node* node){
|
||||
parent->color = 0;
|
||||
grandParent->color = 1;
|
||||
}
|
||||
else{ // Right Left Case
|
||||
else
|
||||
{ // Right Left Case
|
||||
// First step -> Parent Child Rotation
|
||||
parent->left = child->right;
|
||||
if(child->right != NULL){
|
||||
if (child->right != NULL)
|
||||
{
|
||||
(child->right)->par = parent;
|
||||
}
|
||||
child->right = parent;
|
||||
@ -150,7 +178,8 @@ void checkNode(Node* node){
|
||||
|
||||
// Second step -> Child and GrandParent Rotation
|
||||
grandParent->right = child->left;
|
||||
if(child->left != NULL){
|
||||
if (child->left != NULL)
|
||||
{
|
||||
(child->left)->par = grandParent;
|
||||
}
|
||||
child->left = grandParent;
|
||||
@ -158,11 +187,15 @@ void checkNode(Node* node){
|
||||
|
||||
// Attach to the existing tree
|
||||
child->par = greatGrandParent;
|
||||
if(greatGrandParent != NULL){
|
||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
||||
if (greatGrandParent != NULL)
|
||||
{
|
||||
if (greatGrandParent->left != NULL &&
|
||||
greatGrandParent->left == grandParent)
|
||||
{
|
||||
greatGrandParent->left = child;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
greatGrandParent->right = child;
|
||||
}
|
||||
}
|
||||
@ -172,11 +205,14 @@ void checkNode(Node* node){
|
||||
grandParent->color = 1;
|
||||
}
|
||||
}
|
||||
else{ // Left Case
|
||||
else
|
||||
{ // Left Case
|
||||
// Left Left Case
|
||||
if(parent->left == node){
|
||||
if (parent->left == node)
|
||||
{
|
||||
grandParent->left = parent->right;
|
||||
if(parent->right != NULL){
|
||||
if (parent->right != NULL)
|
||||
{
|
||||
(parent->right)->par = grandParent;
|
||||
}
|
||||
parent->right = grandParent;
|
||||
@ -184,11 +220,15 @@ void checkNode(Node* node){
|
||||
|
||||
// Attach to existing Tree;
|
||||
parent->par = greatGrandParent;
|
||||
if(greatGrandParent != NULL){
|
||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
||||
if (greatGrandParent != NULL)
|
||||
{
|
||||
if (greatGrandParent->left != NULL &&
|
||||
greatGrandParent->left == grandParent)
|
||||
{
|
||||
greatGrandParent->left = parent;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
greatGrandParent->right = parent;
|
||||
}
|
||||
}
|
||||
@ -197,11 +237,13 @@ void checkNode(Node* node){
|
||||
parent->color = 0;
|
||||
grandParent->color = 1;
|
||||
}
|
||||
else{ //Left Right Case
|
||||
else
|
||||
{ // Left Right Case
|
||||
|
||||
// First step -> Parent Child Rotation
|
||||
parent->right = child->left;
|
||||
if(child->left != NULL){
|
||||
if (child->left != NULL)
|
||||
{
|
||||
(child->left)->par = parent;
|
||||
}
|
||||
child->left = parent;
|
||||
@ -209,7 +251,8 @@ void checkNode(Node* node){
|
||||
|
||||
// Second step -> Child and GrandParent Rotation
|
||||
grandParent->left = child->right;
|
||||
if(child->right != NULL){
|
||||
if (child->right != NULL)
|
||||
{
|
||||
(child->right)->par = grandParent;
|
||||
}
|
||||
child->right = grandParent;
|
||||
@ -217,11 +260,15 @@ void checkNode(Node* node){
|
||||
|
||||
// Attach to the existing tree
|
||||
child->par = greatGrandParent;
|
||||
if(greatGrandParent != NULL){
|
||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
||||
if (greatGrandParent != NULL)
|
||||
{
|
||||
if (greatGrandParent->left != NULL &&
|
||||
greatGrandParent->left == grandParent)
|
||||
{
|
||||
greatGrandParent->left = child;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
greatGrandParent->right = child;
|
||||
}
|
||||
}
|
||||
@ -235,15 +282,20 @@ void checkNode(Node* node){
|
||||
}
|
||||
|
||||
// To insert a node in the existing tree
|
||||
void insertNode(int val, Node** root){
|
||||
void insertNode(int val, Node **root)
|
||||
{
|
||||
Node *buffRoot = *root;
|
||||
while(buffRoot){
|
||||
if(buffRoot->val > val){
|
||||
while (buffRoot)
|
||||
{
|
||||
if (buffRoot->val > val)
|
||||
{
|
||||
// Go left
|
||||
if(buffRoot->left != NULL){
|
||||
if (buffRoot->left != NULL)
|
||||
{
|
||||
buffRoot = buffRoot->left;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
// Insert The Node
|
||||
Node *toInsert = newNode(val, buffRoot);
|
||||
buffRoot->left = toInsert;
|
||||
@ -253,13 +305,16 @@ void insertNode(int val, Node** root){
|
||||
break;
|
||||
}
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
|
||||
// Go right
|
||||
if(buffRoot->right != NULL){
|
||||
if (buffRoot->right != NULL)
|
||||
{
|
||||
buffRoot = buffRoot->right;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
// Insert The Node
|
||||
Node *toInsert = newNode(val, buffRoot);
|
||||
buffRoot->right = toInsert;
|
||||
@ -271,35 +326,44 @@ void insertNode(int val, Node** root){
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
while(buffRoot != *root){
|
||||
while (buffRoot != *root)
|
||||
{
|
||||
checkNode(buffRoot);
|
||||
if(buffRoot->par == NULL){
|
||||
if (buffRoot->par == NULL)
|
||||
{
|
||||
*root = buffRoot;
|
||||
break;
|
||||
}
|
||||
buffRoot = buffRoot->par;
|
||||
if(buffRoot == *root){
|
||||
if (buffRoot == *root)
|
||||
{
|
||||
buffRoot->color = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
|
||||
{
|
||||
|
||||
if(toDelete == (*root)){
|
||||
if (toDelete == (*root))
|
||||
{
|
||||
(*root)->color = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if(!delete && toDelete->color == 1){
|
||||
if(!fromDirection){
|
||||
if(toDelete->right != NULL){
|
||||
if (!delete &&toDelete->color == 1)
|
||||
{
|
||||
if (!fromDirection)
|
||||
{
|
||||
if (toDelete->right != NULL)
|
||||
{
|
||||
toDelete->right->color = 1;
|
||||
}
|
||||
}
|
||||
else{
|
||||
if(toDelete->left != NULL){
|
||||
else
|
||||
{
|
||||
if (toDelete->left != NULL)
|
||||
{
|
||||
toDelete->left->color = 1;
|
||||
}
|
||||
}
|
||||
@ -307,25 +371,30 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
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){
|
||||
if (parent->right == toDelete)
|
||||
{
|
||||
sibling = parent->left;
|
||||
locateChild = 1;
|
||||
}
|
||||
else{
|
||||
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){
|
||||
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){
|
||||
if (locateChild == 1)
|
||||
{
|
||||
|
||||
int parColor = parent->color;
|
||||
|
||||
@ -336,7 +405,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent = rightRotate(sibling);
|
||||
|
||||
// Check if the root is rotated
|
||||
if(parent->par == NULL){
|
||||
if (parent->par == NULL)
|
||||
{
|
||||
*root = parent;
|
||||
}
|
||||
|
||||
@ -346,16 +416,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent->right->color = 0;
|
||||
|
||||
// Delete the node (present at parent->right->right)
|
||||
if(delete){
|
||||
if(toDelete->left != NULL){
|
||||
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
|
||||
else
|
||||
{ // Sibling is right and child is also right. i.e. LEFT LEFT
|
||||
// ROTATION
|
||||
|
||||
int parColor = parent->color;
|
||||
|
||||
@ -363,7 +436,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent = leftRotate(sibling);
|
||||
|
||||
// Check if the root is rotated
|
||||
if(parent->par == NULL){
|
||||
if (parent->par == NULL)
|
||||
{
|
||||
*root = parent;
|
||||
}
|
||||
|
||||
@ -373,20 +447,23 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent->right->color = 0;
|
||||
|
||||
// Delete the node (present at parent->left->left)
|
||||
if(delete){
|
||||
if(toDelete->right != NULL){
|
||||
if (delete)
|
||||
{
|
||||
if (toDelete->right != NULL)
|
||||
{
|
||||
toDelete->right->par = parent->left;
|
||||
}
|
||||
parent->left->left = toDelete->left;
|
||||
free(toDelete);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
|
||||
// Sibling is right and child is left. i.e. RIGHT LEFT ROTATION
|
||||
if(locateChild == 0){
|
||||
if (locateChild == 0)
|
||||
{
|
||||
|
||||
int parColor = parent->color;
|
||||
|
||||
@ -400,7 +477,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent = leftRotate(sibling);
|
||||
|
||||
// Check if the root is rotated
|
||||
if(parent->par == NULL){
|
||||
if (parent->par == NULL)
|
||||
{
|
||||
*root = parent;
|
||||
}
|
||||
|
||||
@ -410,17 +488,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent->right->color = 0;
|
||||
|
||||
// Delete the node (present at parent->left->left)
|
||||
if(delete){
|
||||
if(toDelete->right != NULL){
|
||||
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
|
||||
else
|
||||
{ // Sibling is left and child is also left. i.e. RIGHT RIGHT
|
||||
// ROTATION
|
||||
|
||||
int parColor = parent->color;
|
||||
|
||||
@ -428,7 +508,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent = rightRotate(sibling);
|
||||
|
||||
// Check if the root is rotated
|
||||
if(parent->par == NULL){
|
||||
if (parent->par == NULL)
|
||||
{
|
||||
*root = parent;
|
||||
}
|
||||
|
||||
@ -438,33 +519,40 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent->right->color = 0;
|
||||
|
||||
// Delete the node (present at parent->right->right)
|
||||
if(delete){
|
||||
if(toDelete->left != NULL){
|
||||
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
|
||||
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){
|
||||
if (delete)
|
||||
{
|
||||
if (locateChild)
|
||||
{
|
||||
toDelete->par->right = toDelete->left;
|
||||
if(toDelete->left != NULL){
|
||||
if (toDelete->left != NULL)
|
||||
{
|
||||
toDelete->left->par = toDelete->par;
|
||||
}
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
toDelete->par->left = toDelete->right;
|
||||
if(toDelete->right != NULL){
|
||||
if (toDelete->right != NULL)
|
||||
{
|
||||
toDelete->right->par = toDelete->par;
|
||||
}
|
||||
}
|
||||
@ -472,18 +560,22 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
|
||||
checkForCase2(parent, 0, locateChild, root);
|
||||
}
|
||||
else{ // Bring the sibling on top and apply 2.1 or 2.2 accordingly
|
||||
if(locateChild){ //Right Rotate
|
||||
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){
|
||||
if (toDelete->left != NULL)
|
||||
{
|
||||
toDelete->left->par = toDelete->par;
|
||||
}
|
||||
|
||||
parent = rightRotate(sibling);
|
||||
|
||||
// Check if the root is rotated
|
||||
if(parent->par == NULL){
|
||||
if (parent->par == NULL)
|
||||
{
|
||||
*root = parent;
|
||||
}
|
||||
|
||||
@ -491,16 +583,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
parent->right->color = 1;
|
||||
checkForCase2(parent->right, 0, 1, root);
|
||||
}
|
||||
else{ // Left Rotate
|
||||
else
|
||||
{ // Left Rotate
|
||||
|
||||
toDelete->par->left = toDelete->right;
|
||||
if(toDelete->right != NULL){
|
||||
if (toDelete->right != NULL)
|
||||
{
|
||||
toDelete->right->par = toDelete->par;
|
||||
}
|
||||
parent = leftRotate(sibling);
|
||||
|
||||
// Check if the root is rotated
|
||||
if(parent->par == NULL){
|
||||
if (parent->par == NULL)
|
||||
{
|
||||
*root = parent;
|
||||
}
|
||||
|
||||
@ -511,35 +606,43 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
||||
checkForCase2(parent->left, 0, 0, root);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// To delete a node from the tree
|
||||
void deleteNode(int val, Node** root){
|
||||
void deleteNode(int val, Node **root)
|
||||
{
|
||||
Node *buffRoot = *root;
|
||||
|
||||
// Search for the element in the tree
|
||||
while(1){
|
||||
while (1)
|
||||
{
|
||||
|
||||
if(val == buffRoot->val){
|
||||
if (val == buffRoot->val)
|
||||
{
|
||||
// Node Found
|
||||
break;
|
||||
}
|
||||
|
||||
if(val > buffRoot->val){
|
||||
if(buffRoot->right != NULL){
|
||||
if (val > buffRoot->val)
|
||||
{
|
||||
if (buffRoot->right != NULL)
|
||||
{
|
||||
buffRoot = buffRoot->right;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
printf("Node Not Found!!!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else{
|
||||
if(buffRoot->left != NULL){
|
||||
else
|
||||
{
|
||||
if (buffRoot->left != NULL)
|
||||
{
|
||||
buffRoot = buffRoot->left;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
printf("Node Not Found!!!");
|
||||
return;
|
||||
}
|
||||
@ -549,20 +652,25 @@ void deleteNode(int val, Node** root){
|
||||
Node *toDelete = buffRoot;
|
||||
|
||||
// Look for the leftmost of right node or right most of left node
|
||||
if(toDelete->left != NULL){
|
||||
if (toDelete->left != NULL)
|
||||
{
|
||||
toDelete = toDelete->left;
|
||||
while(toDelete->right != NULL){
|
||||
while (toDelete->right != NULL)
|
||||
{
|
||||
toDelete = toDelete->right;
|
||||
}
|
||||
}
|
||||
else if(toDelete->right != NULL){
|
||||
else if (toDelete->right != NULL)
|
||||
{
|
||||
toDelete = toDelete->right;
|
||||
while(toDelete->left != NULL){
|
||||
while (toDelete->left != NULL)
|
||||
{
|
||||
toDelete = toDelete->left;
|
||||
}
|
||||
}
|
||||
|
||||
if(toDelete == *root){
|
||||
if (toDelete == *root)
|
||||
{
|
||||
*root = NULL;
|
||||
return;
|
||||
}
|
||||
@ -572,28 +680,37 @@ void deleteNode(int val, Node** root){
|
||||
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 (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){
|
||||
if (toDelete->left == NULL && toDelete->right == NULL)
|
||||
{
|
||||
// Delete instantly
|
||||
if(toDelete->par->left == toDelete){
|
||||
if (toDelete->par->left == toDelete)
|
||||
{
|
||||
toDelete->par->left = NULL;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
toDelete->par->right = NULL;
|
||||
}
|
||||
}
|
||||
else{ // else its child should be red
|
||||
else
|
||||
{ // else its child should be red
|
||||
|
||||
// Check for the exitstence of left node
|
||||
if(toDelete->left != NULL){
|
||||
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
|
||||
else
|
||||
{ // else the right node should be red
|
||||
toDelete->par->left = toDelete->right;
|
||||
toDelete->right->par = toDelete->par;
|
||||
toDelete->right->color = 1;
|
||||
@ -603,49 +720,58 @@ void deleteNode(int val, Node** root){
|
||||
// Remove the node from memory
|
||||
free(toDelete);
|
||||
}
|
||||
else{ // Case 2
|
||||
else
|
||||
{ // Case 2
|
||||
checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
void printInorder(Node* root){
|
||||
if(root != NULL){
|
||||
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){
|
||||
void checkBlack(Node *temp, int c)
|
||||
{
|
||||
if (temp == NULL)
|
||||
{
|
||||
printf("%d ", c);
|
||||
return;
|
||||
}
|
||||
if (temp->color==0){
|
||||
if (temp->color == 0)
|
||||
{
|
||||
c++;
|
||||
}
|
||||
checkBlack(temp->left, c);
|
||||
checkBlack(temp->right, c);
|
||||
}
|
||||
|
||||
int main(){
|
||||
int main()
|
||||
{
|
||||
Node *root = NULL;
|
||||
int scanValue, choice = 1;
|
||||
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - ");
|
||||
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease "
|
||||
"Enter the Choice - ");
|
||||
scanf("%d", &choice);
|
||||
while(choice){
|
||||
switch(choice){
|
||||
while (choice)
|
||||
{
|
||||
switch (choice)
|
||||
{
|
||||
case 1:
|
||||
printf("\n\nPlease Enter A Value to insert - ");
|
||||
scanf("%d", &scanValue);
|
||||
if(root == NULL){
|
||||
if (root == NULL)
|
||||
{
|
||||
root = newNode(scanValue, NULL);
|
||||
root->color = 0;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
insertNode(scanValue, &root);
|
||||
}
|
||||
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
|
||||
@ -664,15 +790,15 @@ int main(){
|
||||
// printf("\n");
|
||||
break;
|
||||
default:
|
||||
if(root != NULL){
|
||||
if (root != NULL)
|
||||
{
|
||||
printf("Root - %d\n", root->val);
|
||||
}
|
||||
}
|
||||
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - ");
|
||||
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
|
||||
|
@ -1,7 +1,6 @@
|
||||
#include "dict.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "dict.h"
|
||||
|
||||
|
||||
/* simple constructor */
|
||||
Dictionary *create_dict(void)
|
||||
@ -26,7 +25,6 @@ Dictionary * create_dict(void)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
utility function
|
||||
sdbm hash algorithm
|
||||
@ -40,14 +38,14 @@ int get_hash(char s[])
|
||||
for (int counter = 0; s[counter] != '\0'; counter++)
|
||||
{
|
||||
/* actual computing of the hash code */
|
||||
hash_code = s[counter] + (hash_code << 6) + (hash_code << 16) - hash_code;
|
||||
hash_code =
|
||||
s[counter] + (hash_code << 6) + (hash_code << 16) - hash_code;
|
||||
}
|
||||
|
||||
/* % modulo is for fitting the index in array. */
|
||||
return hash_code % MAXELEMENTS;
|
||||
}
|
||||
|
||||
|
||||
int add_item_label(Dictionary *dic, char label[], void *item)
|
||||
{
|
||||
unsigned int index = get_hash(label);
|
||||
@ -63,7 +61,6 @@ int add_item_label(Dictionary * dic,char label[],void * item)
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
int add_item_index(Dictionary *dic, int index, void *item)
|
||||
{
|
||||
/* make sure whether this place is already given */
|
||||
@ -77,7 +74,6 @@ int add_item_index(Dictionary * dic , int index, void * item)
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
void *get_element_label(Dictionary *dict, char s[])
|
||||
{
|
||||
int index = get_hash(s);
|
||||
@ -90,7 +86,6 @@ void * get_element_label(Dictionary * dict, char s[])
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
void *get_element_index(Dictionary *dict, int index)
|
||||
{
|
||||
if (index >= 0 && index < MAXELEMENTS)
|
||||
@ -102,8 +97,4 @@ void * get_element_index(Dictionary * dict, int index)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
void destroy(Dictionary * dict)
|
||||
{
|
||||
free(dict);
|
||||
}
|
||||
void destroy(Dictionary *dict) { free(dict); }
|
@ -47,13 +47,11 @@ int add_item_label(Dictionary *,char label[],void *);
|
||||
*/
|
||||
int add_item_index(Dictionary *, int index, void *);
|
||||
|
||||
|
||||
/*
|
||||
get_element: returns the element at given label
|
||||
*/
|
||||
void *get_element_label(Dictionary *, char[]);
|
||||
|
||||
|
||||
/*
|
||||
get_element: returns the element at given index
|
||||
*/
|
||||
@ -64,5 +62,4 @@ void * get_element_index(Dictionary *, int );
|
||||
*/
|
||||
void destroy(Dictionary *);
|
||||
|
||||
|
||||
#endif
|
@ -21,7 +21,6 @@ int main(void)
|
||||
add_item_label(testObj1, "age", &value);
|
||||
add_item_label(testObj2, "name", "Christian");
|
||||
|
||||
|
||||
/*
|
||||
test for function add_item_label
|
||||
|
||||
@ -35,7 +34,8 @@ int main(void)
|
||||
/* test for function add_item_index */
|
||||
if (!add_item_index(testObj1, 0, &value))
|
||||
{
|
||||
printf("My age at index %d is %d\n",0,*((int *)get_element_index(testObj1,0)));
|
||||
printf("My age at index %d is %d\n", 0,
|
||||
*((int *)get_element_index(testObj1, 0)));
|
||||
}
|
||||
|
||||
/* error scenario */
|
||||
|
@ -1,7 +1,7 @@
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include "dynamic_array.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
dynamic_array_t *init_dynamic_array()
|
||||
{
|
||||
@ -14,8 +14,10 @@ dynamic_array_t *init_dynamic_array()
|
||||
|
||||
void *add(dynamic_array_t *da, const void *value)
|
||||
{
|
||||
if (da->size >= da->capacity) {
|
||||
void **newItems = realloc(da->items, (da->capacity <<= 1) * sizeof(void **));
|
||||
if (da->size >= da->capacity)
|
||||
{
|
||||
void **newItems =
|
||||
realloc(da->items, (da->capacity <<= 1) * sizeof(void **));
|
||||
free(da->items);
|
||||
|
||||
da->items = newItems;
|
||||
@ -52,7 +54,8 @@ void delete (dynamic_array_t *da, const unsigned index)
|
||||
if (!contains(da->size, index))
|
||||
return;
|
||||
|
||||
for (unsigned i = index; i < da->size; i++) {
|
||||
for (unsigned i = index; i < da->size; i++)
|
||||
{
|
||||
da->items[i] = da->items[i + 1];
|
||||
}
|
||||
|
||||
|
@ -3,7 +3,8 @@
|
||||
#define DEFAULT_CAPACITY 1 << 4
|
||||
#define INDEX_OUT_OF_BOUNDS NULL
|
||||
|
||||
typedef struct dynamic_array {
|
||||
typedef struct dynamic_array
|
||||
{
|
||||
void **items;
|
||||
unsigned size;
|
||||
unsigned capacity;
|
||||
|
@ -6,7 +6,8 @@ int main()
|
||||
{
|
||||
dynamic_array_t *da = init_dynamic_array();
|
||||
|
||||
for (int i = 1; i <= 50; i++) {
|
||||
for (int i = 1; i <= 50; i++)
|
||||
{
|
||||
add(da, &i);
|
||||
}
|
||||
|
||||
@ -22,7 +23,8 @@ int main()
|
||||
|
||||
add(da, &another_value);
|
||||
|
||||
for (int i = 0; i < da->size; i++) {
|
||||
for (int i = 0; i < da->size; i++)
|
||||
{
|
||||
printf("value %d\n", *(int *)get(da, i));
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,8 @@
|
||||
#include <stdlib.h>
|
||||
#define SIZE 40
|
||||
// Assume max size of graph is 40 nodes
|
||||
struct queue {
|
||||
struct queue
|
||||
{
|
||||
int items[SIZE];
|
||||
int front;
|
||||
int rear;
|
||||
@ -80,16 +81,20 @@ void bfs(struct Graph* graph, int startVertex)
|
||||
printf("Breadth first traversal from vertex %d is:\n", startVertex);
|
||||
|
||||
// Iterate while queue not empty
|
||||
while(!isEmpty(q)){
|
||||
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) {
|
||||
// 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){
|
||||
if (graph->visited[adjVertex] == 0)
|
||||
{
|
||||
graph->visited[adjVertex] = 1;
|
||||
enqueue(q, adjVertex);
|
||||
}
|
||||
@ -115,7 +120,8 @@ struct Graph* createGraph(int vertices)
|
||||
graph->visited = malloc(vertices * sizeof(int));
|
||||
|
||||
int i;
|
||||
for (i = 0; i < vertices; i++) {
|
||||
for (i = 0; i < vertices; i++)
|
||||
{
|
||||
graph->adjLists[i] = NULL;
|
||||
graph->visited[i] = 0;
|
||||
}
|
||||
@ -156,7 +162,8 @@ void enqueue(struct queue* q, int value)
|
||||
{
|
||||
if (q->rear == SIZE - 1)
|
||||
printf("\nQueue is Full!!");
|
||||
else {
|
||||
else
|
||||
{
|
||||
if (q->front == -1)
|
||||
q->front = 0;
|
||||
q->rear++;
|
||||
@ -167,14 +174,17 @@ void enqueue(struct queue* q, int value)
|
||||
int dequeue(struct queue *q)
|
||||
{
|
||||
int item;
|
||||
if(isEmpty(q)){
|
||||
if (isEmpty(q))
|
||||
{
|
||||
printf("Queue is empty");
|
||||
item = -1;
|
||||
}
|
||||
else{
|
||||
else
|
||||
{
|
||||
item = q->items[q->front];
|
||||
q->front++;
|
||||
if(q->front > q->rear){
|
||||
if (q->front > q->rear)
|
||||
{
|
||||
q->front = q->rear = -1;
|
||||
}
|
||||
}
|
||||
@ -182,7 +192,4 @@ int dequeue(struct queue* q)
|
||||
}
|
||||
|
||||
// Returns element at front of queue
|
||||
int pollQueue(struct queue *q)
|
||||
{
|
||||
return q->items[q->front];
|
||||
}
|
||||
int pollQueue(struct queue *q) { return q->items[q->front]; }
|
||||
|
@ -1,29 +1,33 @@
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include<limits.h>
|
||||
#include <string.h>
|
||||
|
||||
// Structure for storing edge
|
||||
struct Edge{
|
||||
struct Edge
|
||||
{
|
||||
int src, dst, weight;
|
||||
};
|
||||
|
||||
// Structure for storing a graph
|
||||
struct Graph{
|
||||
struct Graph
|
||||
{
|
||||
int vertexNum;
|
||||
int edgeNum;
|
||||
struct Edge *edges;
|
||||
};
|
||||
|
||||
// Constructs a graph with V vertices and E edges
|
||||
void createGraph(struct Graph* G,int V,int E){
|
||||
void createGraph(struct Graph *G, int V, int E)
|
||||
{
|
||||
G->vertexNum = V;
|
||||
G->edgeNum = E;
|
||||
G->edges = (struct Edge *)malloc(E * sizeof(struct Edge));
|
||||
}
|
||||
|
||||
// Adds the given edge to the graph
|
||||
void addEdge(struct Graph* G, int src, int dst, int weight){
|
||||
void addEdge(struct Graph *G, int src, int dst, int weight)
|
||||
{
|
||||
static int ind;
|
||||
struct Edge newEdge;
|
||||
newEdge.src = src;
|
||||
@ -32,12 +36,13 @@ void addEdge(struct Graph* G, int src, int dst, int weight){
|
||||
G->edges[ind++] = newEdge;
|
||||
}
|
||||
|
||||
|
||||
// Utility function to find minimum distance vertex in mdist
|
||||
int minDistance(int mdist[], int vset[], int V){
|
||||
int minDistance(int mdist[], int vset[], int V)
|
||||
{
|
||||
int minVal = INT_MAX, minInd;
|
||||
for (int i = 0; i < V; i++)
|
||||
if(vset[i] == 0 && mdist[i] < minVal){
|
||||
if (vset[i] == 0 && mdist[i] < minVal)
|
||||
{
|
||||
minVal = mdist[i];
|
||||
minInd = i;
|
||||
}
|
||||
@ -46,9 +51,11 @@ int minDistance(int mdist[], int vset[], int V){
|
||||
}
|
||||
|
||||
// Utility function to print distances
|
||||
void print(int dist[], int V){
|
||||
void print(int dist[], int V)
|
||||
{
|
||||
printf("\nVertex Distance\n");
|
||||
for(int i = 0; i < V; i++){
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (dist[i] != INT_MAX)
|
||||
printf("%d\t%d\n", i, dist[i]);
|
||||
else
|
||||
@ -59,7 +66,8 @@ void print(int dist[], int V){
|
||||
// The main function that finds the shortest path from given source
|
||||
// to all other vertices using Bellman-Ford.It also detects negative
|
||||
// weight cycle
|
||||
void BellmanFord(struct Graph* graph, int src){
|
||||
void BellmanFord(struct Graph *graph, int src)
|
||||
{
|
||||
int V = graph->vertexNum;
|
||||
int E = graph->edgeNum;
|
||||
int dist[V];
|
||||
@ -73,7 +81,8 @@ void BellmanFord(struct Graph* graph, int src){
|
||||
// Calculate shortest path distance from source to all edges
|
||||
// A path can contain maximum (|V|-1) edges
|
||||
for (int i = 0; i <= V - 1; i++)
|
||||
for(int j = 0; j<E; j++){
|
||||
for (int j = 0; j < E; j++)
|
||||
{
|
||||
int u = graph->edges[j].src;
|
||||
int v = graph->edges[j].dst;
|
||||
int w = graph->edges[j].weight;
|
||||
@ -83,13 +92,16 @@ void BellmanFord(struct Graph* graph, int src){
|
||||
}
|
||||
|
||||
// Iterate inner loop once more to check for negative cycle
|
||||
for(int j = 0; j<E; j++){
|
||||
for (int j = 0; j < E; j++)
|
||||
{
|
||||
int u = graph->edges[j].src;
|
||||
int v = graph->edges[j].dst;
|
||||
int w = graph->edges[j].weight;
|
||||
|
||||
if(dist[u]!=INT_MAX && dist[u] + w < dist[v]){
|
||||
printf("Graph contains negative weight cycle. Hence, shortest distance not guaranteed.");
|
||||
if (dist[u] != INT_MAX && dist[u] + w < dist[v])
|
||||
{
|
||||
printf("Graph contains negative weight cycle. Hence, shortest "
|
||||
"distance not guaranteed.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -99,10 +111,9 @@ void BellmanFord(struct Graph* graph, int src){
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Driver Function
|
||||
int main(){
|
||||
int main()
|
||||
{
|
||||
int V, E, gsrc;
|
||||
int src, dst, weight;
|
||||
struct Graph G;
|
||||
@ -111,7 +122,8 @@ int main(){
|
||||
printf("Enter number of edges: ");
|
||||
scanf("%d", &E);
|
||||
createGraph(&G, V, E);
|
||||
for(int i=0; i<E; i++){
|
||||
for (int i = 0; i < E; i++)
|
||||
{
|
||||
printf("\nEdge %d \nEnter source: ", i + 1);
|
||||
scanf("%d", &src);
|
||||
printf("Enter destination: ");
|
||||
@ -126,5 +138,3 @@ int main(){
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
@ -13,7 +13,9 @@ 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 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);
|
||||
@ -55,7 +57,8 @@ int main()
|
||||
return 0;
|
||||
}
|
||||
// Recursive dfs approach
|
||||
void dfs(struct Graph* graph, int vertex) {
|
||||
void dfs(struct Graph *graph, int vertex)
|
||||
{
|
||||
struct node *adjList = graph->adjLists[vertex];
|
||||
struct node *temp = adjList;
|
||||
|
||||
@ -64,9 +67,11 @@ void dfs(struct Graph* graph, int vertex) {
|
||||
printf("%d ", vertex);
|
||||
|
||||
// Recursively call the dfs function on all unvisited neighbours
|
||||
while(temp!=NULL) {
|
||||
while (temp != NULL)
|
||||
{
|
||||
int connectedVertex = temp->vertex;
|
||||
if(graph->visited[connectedVertex] == 0) {
|
||||
if (graph->visited[connectedVertex] == 0)
|
||||
{
|
||||
dfs(graph, connectedVertex);
|
||||
}
|
||||
temp = temp->next;
|
||||
@ -91,7 +96,8 @@ struct Graph* createGraph(int vertices)
|
||||
graph->visited = malloc(vertices * sizeof(int));
|
||||
|
||||
int i;
|
||||
for (i = 0; i < vertices; i++) {
|
||||
for (i = 0; i < vertices; i++)
|
||||
{
|
||||
graph->adjLists[i] = NULL;
|
||||
graph->visited[i] = 0;
|
||||
}
|
||||
|
@ -1,20 +1,22 @@
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include<limits.h>
|
||||
#include <string.h>
|
||||
|
||||
|
||||
// Structure for storing a graph
|
||||
struct Graph{
|
||||
struct Graph
|
||||
{
|
||||
int vertexNum;
|
||||
int **edges;
|
||||
};
|
||||
|
||||
// Constructs a graph with V vertices and E edges
|
||||
void createGraph(struct Graph* G,int V){
|
||||
void createGraph(struct Graph *G, int V)
|
||||
{
|
||||
G->vertexNum = V;
|
||||
G->edges = (int **)malloc(V * sizeof(int *));
|
||||
for(int i=0; i<V; i++){
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
G->edges[i] = (int *)malloc(V * sizeof(int));
|
||||
for (int j = 0; j < V; j++)
|
||||
G->edges[i][j] = INT_MAX;
|
||||
@ -23,16 +25,18 @@ void createGraph(struct Graph* G,int V){
|
||||
}
|
||||
|
||||
// Adds the given edge to the graph
|
||||
void addEdge(struct Graph* G, int src, int dst, int weight){
|
||||
void addEdge(struct Graph *G, int src, int dst, int weight)
|
||||
{
|
||||
G->edges[src][dst] = weight;
|
||||
}
|
||||
|
||||
|
||||
// Utility function to find minimum distance vertex in mdist
|
||||
int minDistance(int mdist[], int vset[], int V){
|
||||
int minDistance(int mdist[], int vset[], int V)
|
||||
{
|
||||
int minVal = INT_MAX, minInd;
|
||||
for (int i = 0; i < V; i++)
|
||||
if(vset[i] == 0 && mdist[i] < minVal){
|
||||
if (vset[i] == 0 && mdist[i] < minVal)
|
||||
{
|
||||
minVal = mdist[i];
|
||||
minInd = i;
|
||||
}
|
||||
@ -41,9 +45,11 @@ int minDistance(int mdist[], int vset[], int V){
|
||||
}
|
||||
|
||||
// Utility function to print distances
|
||||
void print(int dist[], int V){
|
||||
void print(int dist[], int V)
|
||||
{
|
||||
printf("\nVertex Distance\n");
|
||||
for(int i = 0; i < V; i++){
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (dist[i] != INT_MAX)
|
||||
printf("%d\t%d\n", i, dist[i]);
|
||||
else
|
||||
@ -54,7 +60,8 @@ void print(int dist[], int V){
|
||||
// The main function that finds the shortest path from given source
|
||||
// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative
|
||||
// weights
|
||||
void Dijkstra(struct Graph* graph, int src){
|
||||
void Dijkstra(struct Graph *graph, int src)
|
||||
{
|
||||
int V = graph->vertexNum;
|
||||
int mdist[V]; // Stores updated distances to vertex
|
||||
int vset[V]; // vset[i] is true if the vertex i included
|
||||
@ -67,14 +74,16 @@ void Dijkstra(struct Graph* graph, int src){
|
||||
mdist[src] = 0;
|
||||
|
||||
// iterate to find shortest path
|
||||
for(int count = 0; count<V-1; count++){
|
||||
for (int count = 0; count < V - 1; count++)
|
||||
{
|
||||
int u = minDistance(mdist, vset, V);
|
||||
vset[u] = 1;
|
||||
|
||||
for(int v=0; v<V; v++){
|
||||
if(!vset[v] && graph->edges[u][v]!=INT_MAX && mdist[u] + graph->edges[u][v] < mdist[v])
|
||||
for (int v = 0; v < V; v++)
|
||||
{
|
||||
if (!vset[v] && graph->edges[u][v] != INT_MAX &&
|
||||
mdist[u] + graph->edges[u][v] < mdist[v])
|
||||
mdist[v] = mdist[u] + graph->edges[u][v];
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -83,10 +92,9 @@ void Dijkstra(struct Graph* graph, int src){
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Driver Function
|
||||
int main(){
|
||||
int main()
|
||||
{
|
||||
int V, E, gsrc;
|
||||
int src, dst, weight;
|
||||
struct Graph G;
|
||||
@ -95,7 +103,8 @@ int main(){
|
||||
printf("Enter number of edges: ");
|
||||
scanf("%d", &E);
|
||||
createGraph(&G, V);
|
||||
for(int i=0; i<E; i++){
|
||||
for (int i = 0; i < E; i++)
|
||||
{
|
||||
printf("\nEdge %d \nEnter source: ", i + 1);
|
||||
scanf("%d", &src);
|
||||
printf("Enter destination: ");
|
||||
@ -110,5 +119,3 @@ int main(){
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,20 +1,22 @@
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include<limits.h>
|
||||
#include <string.h>
|
||||
|
||||
|
||||
// Structure for storing a graph
|
||||
struct Graph{
|
||||
struct Graph
|
||||
{
|
||||
int vertexNum;
|
||||
int **edges;
|
||||
};
|
||||
|
||||
// Constructs a graph with V vertices and E edges
|
||||
void createGraph(struct Graph* G,int V){
|
||||
void createGraph(struct Graph *G, int V)
|
||||
{
|
||||
G->vertexNum = V;
|
||||
G->edges = (int **)malloc(V * sizeof(int *));
|
||||
for(int i=0; i<V; i++){
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
G->edges[i] = (int *)malloc(V * sizeof(int));
|
||||
for (int j = 0; j < V; j++)
|
||||
G->edges[i][j] = INT_MAX;
|
||||
@ -23,16 +25,19 @@ void createGraph(struct Graph* G,int V){
|
||||
}
|
||||
|
||||
// Adds the given edge to the graph
|
||||
void addEdge(struct Graph* G, int src, int dst, int weight){
|
||||
void addEdge(struct Graph *G, int src, int dst, int weight)
|
||||
{
|
||||
G->edges[src][dst] = weight;
|
||||
}
|
||||
|
||||
|
||||
// Utility function to print distances
|
||||
void print(int dist[], int V){
|
||||
void print(int dist[], int V)
|
||||
{
|
||||
printf("\nThe Distance matrix for Floyd - Warshall\n");
|
||||
for(int i = 0; i < V; i++){
|
||||
for(int j=0; j<V; j++){
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
for (int j = 0; j < V; j++)
|
||||
{
|
||||
|
||||
if (dist[i * V + j] != INT_MAX)
|
||||
printf("%d\t", dist[i * V + j]);
|
||||
@ -45,7 +50,8 @@ void print(int dist[], int V){
|
||||
|
||||
// The main function that finds the shortest path from a vertex
|
||||
// to all other vertices using Floyd-Warshall Algorithm.
|
||||
void FloydWarshall(struct Graph* graph){
|
||||
void FloydWarshall(struct Graph *graph)
|
||||
{
|
||||
int V = graph->vertexNum;
|
||||
int dist[V][V];
|
||||
|
||||
@ -54,7 +60,6 @@ void FloydWarshall(struct Graph* graph){
|
||||
for (int j = 0; j < V; j++)
|
||||
dist[i][j] = graph->edges[i][j];
|
||||
|
||||
|
||||
// Calculate distances
|
||||
for (int k = 0; k < V; k++)
|
||||
// Choose an intermediate vertex
|
||||
@ -65,11 +70,12 @@ void FloydWarshall(struct Graph* graph){
|
||||
for (int j = 0; j < V; j++)
|
||||
// Choose a destination vertex for above source vertex
|
||||
|
||||
if(dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j])
|
||||
//If the distance through intermediate vertex is less than direct edge then update value in distance array
|
||||
if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX &&
|
||||
dist[i][k] + dist[k][j] < dist[i][j])
|
||||
// If the distance through intermediate vertex is less than
|
||||
// direct edge then update value in distance array
|
||||
dist[i][j] = dist[i][k] + dist[k][j];
|
||||
|
||||
|
||||
// Convert 2d array to 1d array for print
|
||||
int dist1d[V * V];
|
||||
for (int i = 0; i < V; i++)
|
||||
@ -80,7 +86,8 @@ void FloydWarshall(struct Graph* graph){
|
||||
}
|
||||
|
||||
// Driver Function
|
||||
int main(){
|
||||
int main()
|
||||
{
|
||||
int V, E;
|
||||
int src, dst, weight;
|
||||
struct Graph G;
|
||||
@ -89,7 +96,8 @@ int main(){
|
||||
printf("Enter number of edges: ");
|
||||
scanf("%d", &E);
|
||||
createGraph(&G, V);
|
||||
for(int i=0; i<E; i++){
|
||||
for (int i = 0; i < E; i++)
|
||||
{
|
||||
printf("\nEdge %d \nEnter source: ", i + 1);
|
||||
scanf("%d", &src);
|
||||
printf("Enter destination: ");
|
||||
|
@ -2,16 +2,18 @@
|
||||
// Adjacency Matrix Representation
|
||||
#include "Graph.h"
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct GraphRep {
|
||||
typedef struct GraphRep
|
||||
{
|
||||
int **edges; // adjacency matrix
|
||||
int nV; // #vertices
|
||||
int nE; // #edges
|
||||
} GraphRep;
|
||||
|
||||
Graph newGraph(int V) {
|
||||
Graph newGraph(int V)
|
||||
{
|
||||
assert(V >= 0);
|
||||
int i;
|
||||
|
||||
@ -24,7 +26,8 @@ Graph newGraph(int V) {
|
||||
g->edges = malloc(V * sizeof(int *));
|
||||
assert(g->edges != NULL);
|
||||
// allocate memory for each column and initialise with 0
|
||||
for (i = 0; i < V; i++) {
|
||||
for (i = 0; i < V; i++)
|
||||
{
|
||||
g->edges[i] = calloc(V, sizeof(int));
|
||||
assert(g->edges[i] != NULL);
|
||||
}
|
||||
@ -33,37 +36,41 @@ Graph newGraph(int V) {
|
||||
}
|
||||
|
||||
// check if vertex is valid in a graph
|
||||
bool validV(Graph g, Vertex v) {
|
||||
return (g != NULL && v >= 0 && v < g->nV);
|
||||
}
|
||||
bool validV(Graph g, Vertex v) { return (g != NULL && v >= 0 && v < g->nV); }
|
||||
|
||||
void insertEdge(Graph g, Edge e) {
|
||||
void insertEdge(Graph g, Edge e)
|
||||
{
|
||||
assert(g != NULL && validV(g, e.v) && validV(g, e.w));
|
||||
|
||||
if (!g->edges[e.v][e.w]) { // edge e not in graph
|
||||
if (!g->edges[e.v][e.w])
|
||||
{ // edge e not in graph
|
||||
g->edges[e.v][e.w] = 1;
|
||||
g->edges[e.w][e.v] = 1;
|
||||
g->nE++;
|
||||
}
|
||||
}
|
||||
|
||||
void removeEdge(Graph g, Edge e) {
|
||||
void removeEdge(Graph g, Edge e)
|
||||
{
|
||||
assert(g != NULL && validV(g, e.v) && validV(g, e.w));
|
||||
|
||||
if (g->edges[e.v][e.w]) { // edge e in graph
|
||||
if (g->edges[e.v][e.w])
|
||||
{ // edge e in graph
|
||||
g->edges[e.v][e.w] = 0;
|
||||
g->edges[e.w][e.v] = 0;
|
||||
g->nE--;
|
||||
}
|
||||
}
|
||||
|
||||
bool adjacent(Graph g, Vertex v, Vertex w) {
|
||||
bool adjacent(Graph g, Vertex v, Vertex w)
|
||||
{
|
||||
assert(g != NULL && validV(g, v) && validV(g, w));
|
||||
|
||||
return (g->edges[v][w] != 0);
|
||||
}
|
||||
|
||||
void showGraph(Graph g) {
|
||||
void showGraph(Graph g)
|
||||
{
|
||||
assert(g != NULL);
|
||||
int i, j;
|
||||
|
||||
@ -75,7 +82,8 @@ void showGraph(Graph g) {
|
||||
printf("Edge %d - %d\n", i, j);
|
||||
}
|
||||
|
||||
void freeGraph(Graph g) {
|
||||
void freeGraph(Graph g)
|
||||
{
|
||||
assert(g != NULL);
|
||||
|
||||
int i;
|
||||
@ -86,17 +94,25 @@ void freeGraph(Graph g) {
|
||||
}
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -7,7 +7,8 @@ typedef struct GraphRep *Graph;
|
||||
typedef int Vertex;
|
||||
|
||||
// edges are pairs of vertices (end-points)
|
||||
typedef struct Edge {
|
||||
typedef struct Edge
|
||||
{
|
||||
Vertex v;
|
||||
Vertex w;
|
||||
} Edge;
|
||||
@ -19,19 +20,26 @@ bool adjacent(Graph, Vertex, Vertex);
|
||||
void showGraph(Graph);
|
||||
void freeGraph(Graph);
|
||||
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -1,14 +1,15 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include "queue.h"
|
||||
#include "Graph.h"
|
||||
#include "queue.h"
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define MAX_NODES 1000
|
||||
|
||||
int visited[MAX_NODES]; // array to store visiting order
|
||||
// indexed by vertex 0..nV-1
|
||||
|
||||
bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest) {
|
||||
bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest)
|
||||
{
|
||||
Vertex v;
|
||||
for (v = 0; v < nV; v++)
|
||||
visited[v] = -1;
|
||||
@ -16,11 +17,13 @@ bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest) {
|
||||
visited[src] = src;
|
||||
queue Q = newQueue();
|
||||
QueueEnqueue(Q, src);
|
||||
while (!QueueIsEmpty(Q)) {
|
||||
while (!QueueIsEmpty(Q))
|
||||
{
|
||||
v = QueueDequeue(Q);
|
||||
Vertex w;
|
||||
for (w = 0; w < nV; w++)
|
||||
if (adjacent(g, v, w) && visited[w] == -1) {
|
||||
if (adjacent(g, v, w) && visited[w] == -1)
|
||||
{
|
||||
visited[w] = v;
|
||||
if (w == dest)
|
||||
return true;
|
||||
@ -31,31 +34,64 @@ bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int main(void)
|
||||
{
|
||||
int V = 10;
|
||||
Graph g = newGraph(V);
|
||||
|
||||
Edge e;
|
||||
e.v = 0; e.w = 1; insertEdge(g, e);
|
||||
e.v = 0; e.w = 2; insertEdge(g, e);
|
||||
e.v = 0; e.w = 5; insertEdge(g, e);
|
||||
e.v = 1; e.w = 5; insertEdge(g, e);
|
||||
e.v = 2; e.w = 3; insertEdge(g, e);
|
||||
e.v = 3; e.w = 4; insertEdge(g, e);
|
||||
e.v = 3; e.w = 5; insertEdge(g, e);
|
||||
e.v = 3; e.w = 8; insertEdge(g, e);
|
||||
e.v = 4; e.w = 5; insertEdge(g, e);
|
||||
e.v = 4; e.w = 7; insertEdge(g, e);
|
||||
e.v = 4; e.w = 8; insertEdge(g, e);
|
||||
e.v = 5; e.w = 6; insertEdge(g, e);
|
||||
e.v = 7; e.w = 8; insertEdge(g, e);
|
||||
e.v = 7; e.w = 9; insertEdge(g, e);
|
||||
e.v = 8; e.w = 9; insertEdge(g, e);
|
||||
e.v = 0;
|
||||
e.w = 1;
|
||||
insertEdge(g, e);
|
||||
e.v = 0;
|
||||
e.w = 2;
|
||||
insertEdge(g, e);
|
||||
e.v = 0;
|
||||
e.w = 5;
|
||||
insertEdge(g, e);
|
||||
e.v = 1;
|
||||
e.w = 5;
|
||||
insertEdge(g, e);
|
||||
e.v = 2;
|
||||
e.w = 3;
|
||||
insertEdge(g, e);
|
||||
e.v = 3;
|
||||
e.w = 4;
|
||||
insertEdge(g, e);
|
||||
e.v = 3;
|
||||
e.w = 5;
|
||||
insertEdge(g, e);
|
||||
e.v = 3;
|
||||
e.w = 8;
|
||||
insertEdge(g, e);
|
||||
e.v = 4;
|
||||
e.w = 5;
|
||||
insertEdge(g, e);
|
||||
e.v = 4;
|
||||
e.w = 7;
|
||||
insertEdge(g, e);
|
||||
e.v = 4;
|
||||
e.w = 8;
|
||||
insertEdge(g, e);
|
||||
e.v = 5;
|
||||
e.w = 6;
|
||||
insertEdge(g, e);
|
||||
e.v = 7;
|
||||
e.w = 8;
|
||||
insertEdge(g, e);
|
||||
e.v = 7;
|
||||
e.w = 9;
|
||||
insertEdge(g, e);
|
||||
e.v = 8;
|
||||
e.w = 9;
|
||||
insertEdge(g, e);
|
||||
|
||||
int src = 0, dest = 6;
|
||||
if (findPathBFS(g, V, src, dest)) {
|
||||
if (findPathBFS(g, V, src, dest))
|
||||
{
|
||||
Vertex v = dest;
|
||||
while (v != src) {
|
||||
while (v != src)
|
||||
{
|
||||
printf("%d - ", v);
|
||||
v = visited[v];
|
||||
}
|
||||
@ -65,17 +101,25 @@ int main(void) {
|
||||
}
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -1,16 +1,18 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include "Graph.h"
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define MAX_NODES 1000
|
||||
|
||||
int visited[MAX_NODES]; // array to store visiting order
|
||||
// indexed by vertex 0..nV-1
|
||||
|
||||
bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest) {
|
||||
bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest)
|
||||
{
|
||||
Vertex w;
|
||||
for (w = 0; w < nV; w++)
|
||||
if (adjacent(g, v, w) && visited[w] == -1) {
|
||||
if (adjacent(g, v, w) && visited[w] == -1)
|
||||
{
|
||||
visited[w] = v;
|
||||
if (w == dest)
|
||||
return true;
|
||||
@ -20,7 +22,8 @@ bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest) {
|
||||
bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest)
|
||||
{
|
||||
Vertex v;
|
||||
for (v = 0; v < nV; v++)
|
||||
visited[v] = -1;
|
||||
@ -28,25 +31,46 @@ bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest) {
|
||||
return dfsPathCheck(g, nV, src, dest);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int main(void)
|
||||
{
|
||||
int V = 6;
|
||||
Graph g = newGraph(V);
|
||||
|
||||
Edge e;
|
||||
e.v = 0; e.w = 1; insertEdge(g, e);
|
||||
e.v = 0; e.w = 4; insertEdge(g, e);
|
||||
e.v = 0; e.w = 5; insertEdge(g, e);
|
||||
e.v = 5; e.w = 4; insertEdge(g, e);
|
||||
e.v = 4; e.w = 2; insertEdge(g, e);
|
||||
e.v = 4; e.w = 3; insertEdge(g, e);
|
||||
e.v = 5; e.w = 3; insertEdge(g, e);
|
||||
e.v = 1; e.w = 2; insertEdge(g, e);
|
||||
e.v = 3; e.w = 2; insertEdge(g, e);
|
||||
e.v = 0;
|
||||
e.w = 1;
|
||||
insertEdge(g, e);
|
||||
e.v = 0;
|
||||
e.w = 4;
|
||||
insertEdge(g, e);
|
||||
e.v = 0;
|
||||
e.w = 5;
|
||||
insertEdge(g, e);
|
||||
e.v = 5;
|
||||
e.w = 4;
|
||||
insertEdge(g, e);
|
||||
e.v = 4;
|
||||
e.w = 2;
|
||||
insertEdge(g, e);
|
||||
e.v = 4;
|
||||
e.w = 3;
|
||||
insertEdge(g, e);
|
||||
e.v = 5;
|
||||
e.w = 3;
|
||||
insertEdge(g, e);
|
||||
e.v = 1;
|
||||
e.w = 2;
|
||||
insertEdge(g, e);
|
||||
e.v = 3;
|
||||
e.w = 2;
|
||||
insertEdge(g, e);
|
||||
|
||||
int src = 0, dest = 5;
|
||||
if (findPathDFS(g, V, src, dest)) {
|
||||
if (findPathDFS(g, V, src, dest))
|
||||
{
|
||||
Vertex v = dest;
|
||||
while (v != src) {
|
||||
while (v != src)
|
||||
{
|
||||
printf("%d - ", v);
|
||||
v = visited[v];
|
||||
}
|
||||
@ -55,20 +79,26 @@ int main(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
||||
|
@ -1,10 +1,11 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include "Graph.h"
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// Return the number of vertices that v is
|
||||
// connected to
|
||||
int degree(Graph g, int nV, Vertex v) {
|
||||
int degree(Graph g, int nV, Vertex v)
|
||||
{
|
||||
int deg = 0;
|
||||
Vertex w;
|
||||
for (w = 0; w < nV; w++)
|
||||
@ -15,11 +16,15 @@ int degree(Graph g, int nV, Vertex v) {
|
||||
|
||||
// If start from vertex v, decide if the
|
||||
// graph has euler path
|
||||
bool hasEulerPath(Graph g, int nV, Vertex v, Vertex w) {
|
||||
if (v != w) {
|
||||
bool hasEulerPath(Graph g, int nV, Vertex v, Vertex w)
|
||||
{
|
||||
if (v != w)
|
||||
{
|
||||
if (degree(g, nV, v) % 2 == 0 || degree(g, nV, w) % 2 == 0)
|
||||
return false;
|
||||
} else if (degree(g, nV, v) % 2 != 0) {
|
||||
}
|
||||
else if (degree(g, nV, v) % 2 != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Vertex x;
|
||||
@ -29,7 +34,8 @@ bool hasEulerPath(Graph g, int nV, Vertex v, Vertex w) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int main(void)
|
||||
{
|
||||
Edge e;
|
||||
int n;
|
||||
|
||||
@ -44,7 +50,8 @@ int main(void) {
|
||||
scanf("%d", &dest);
|
||||
|
||||
printf("Enter an edge (from): ");
|
||||
while (scanf("%d", &e.v) == 1) {
|
||||
while (scanf("%d", &e.v) == 1)
|
||||
{
|
||||
printf("Enter an edge (to): ");
|
||||
scanf("%d", &e.w);
|
||||
insertEdge(g, e);
|
||||
@ -63,20 +70,26 @@ int main(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -1,24 +1,31 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include "Graph.h"
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define MAX_NODES 1000
|
||||
|
||||
bool visited[MAX_NODES];
|
||||
|
||||
bool hamiltonR(Graph g, int nV, Vertex v, Vertex dest, int d) {
|
||||
bool hamiltonR(Graph g, int nV, Vertex v, Vertex dest, int d)
|
||||
{
|
||||
// v = current vertex considered
|
||||
// dest = destination vertex
|
||||
// d = distance "remaining" until path found
|
||||
|
||||
Vertex w;
|
||||
if (v == dest) {
|
||||
if (v == dest)
|
||||
{
|
||||
return (d == 0);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
visited[v] = true;
|
||||
for (w = 0; w < nV; w++) {
|
||||
if (adjacent(g, v, w) && !visited[w]) {
|
||||
if (hamiltonR(g, nV, w, dest, d-1)) {
|
||||
for (w = 0; w < nV; w++)
|
||||
{
|
||||
if (adjacent(g, v, w) && !visited[w])
|
||||
{
|
||||
if (hamiltonR(g, nV, w, dest, d - 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -28,14 +35,16 @@ bool hamiltonR(Graph g, int nV, Vertex v, Vertex dest, int d) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasHamiltonianPath(Graph g, int nV, Vertex src, Vertex dest) {
|
||||
bool hasHamiltonianPath(Graph g, int nV, Vertex src, Vertex dest)
|
||||
{
|
||||
Vertex v;
|
||||
for (v = 0; v < nV; v++)
|
||||
visited[v] = false;
|
||||
return hamiltonR(g, nV, src, dest, nV - 1);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int main(void)
|
||||
{
|
||||
Edge e;
|
||||
int n;
|
||||
|
||||
@ -50,7 +59,8 @@ int main(void) {
|
||||
scanf("%d", &dest);
|
||||
|
||||
printf("Enter an edge (from): ");
|
||||
while (scanf("%d", &e.v) == 1) {
|
||||
while (scanf("%d", &e.v) == 1)
|
||||
{
|
||||
printf("Enter an edge (to): ");
|
||||
scanf("%d", &e.w);
|
||||
insertEdge(g, e);
|
||||
@ -69,19 +79,26 @@ int main(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -102,8 +102,7 @@ void KruskalMST(struct Graph* graph)
|
||||
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) );
|
||||
struct subset *subsets = (struct subset *)malloc(V * sizeof(struct subset));
|
||||
|
||||
// Create V subsets with single elements
|
||||
for (int v = 0; v < V; ++v)
|
||||
@ -157,7 +156,6 @@ int main()
|
||||
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;
|
||||
|
@ -1,22 +1,25 @@
|
||||
// Queue ADT implementation ... COMP2521
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include "queue.h"
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
typedef struct node
|
||||
{
|
||||
int data;
|
||||
struct node *next;
|
||||
} NodeT;
|
||||
|
||||
typedef struct QueueRep {
|
||||
typedef struct QueueRep
|
||||
{
|
||||
int length;
|
||||
NodeT *head;
|
||||
NodeT *tail;
|
||||
} QueueRep;
|
||||
|
||||
// set up empty queue
|
||||
queue newQueue() {
|
||||
queue newQueue()
|
||||
{
|
||||
queue Q = malloc(sizeof(QueueRep));
|
||||
Q->length = 0;
|
||||
Q->head = NULL;
|
||||
@ -25,9 +28,11 @@ queue newQueue() {
|
||||
}
|
||||
|
||||
// remove unwanted queue
|
||||
void dropQueue(queue Q) {
|
||||
void dropQueue(queue Q)
|
||||
{
|
||||
NodeT *curr = Q->head;
|
||||
while (curr != NULL) {
|
||||
while (curr != NULL)
|
||||
{
|
||||
NodeT *temp = curr->next;
|
||||
free(curr);
|
||||
curr = temp;
|
||||
@ -36,20 +41,22 @@ void dropQueue(queue Q) {
|
||||
}
|
||||
|
||||
// check whether queue is empty
|
||||
int QueueIsEmpty(queue Q) {
|
||||
return (Q->length == 0);
|
||||
}
|
||||
int QueueIsEmpty(queue Q) { return (Q->length == 0); }
|
||||
|
||||
// insert an int at end of queue
|
||||
void QueueEnqueue(queue Q, int v) {
|
||||
void QueueEnqueue(queue Q, int v)
|
||||
{
|
||||
NodeT *new = malloc(sizeof(NodeT));
|
||||
assert(new != NULL);
|
||||
new->data = v;
|
||||
new->next = NULL;
|
||||
if (Q->tail != NULL) {
|
||||
if (Q->tail != NULL)
|
||||
{
|
||||
Q->tail->next = new;
|
||||
Q->tail = new;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
Q->head = new;
|
||||
Q->tail = new;
|
||||
}
|
||||
@ -57,11 +64,13 @@ void QueueEnqueue(queue Q, int v) {
|
||||
}
|
||||
|
||||
// remove int from front of queue
|
||||
int QueueDequeue(queue Q) {
|
||||
int QueueDequeue(queue Q)
|
||||
{
|
||||
assert(Q->length > 0);
|
||||
NodeT *p = Q->head;
|
||||
Q->head = Q->head->next;
|
||||
if (Q->head == NULL) {
|
||||
if (Q->head == NULL)
|
||||
{
|
||||
Q->tail = NULL;
|
||||
}
|
||||
Q->length--;
|
||||
@ -70,19 +79,26 @@ int QueueDequeue(queue Q) {
|
||||
return d;
|
||||
}
|
||||
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -8,19 +8,26 @@ int QueueIsEmpty(queue); // check whether queue is empty
|
||||
void QueueEnqueue(queue, int); // insert an int at end of queue
|
||||
int QueueDequeue(queue); // remove int from front of queue
|
||||
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -14,7 +14,9 @@ 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 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
|
||||
@ -71,9 +73,11 @@ void fillOrder(int vertex, struct Graph* graph, struct Stack* stack)
|
||||
struct node *adjList = graph->adjLists[vertex];
|
||||
struct node *temp = adjList;
|
||||
// First add all dependents (that is, children) to stack
|
||||
while(temp!=NULL) {
|
||||
while (temp != NULL)
|
||||
{
|
||||
int connectedVertex = temp->vertex;
|
||||
if(graph->visited[connectedVertex] == 0) {
|
||||
if (graph->visited[connectedVertex] == 0)
|
||||
{
|
||||
fillOrder(connectedVertex, graph, stack);
|
||||
}
|
||||
temp = temp->next;
|
||||
@ -84,7 +88,8 @@ void fillOrder(int vertex, struct Graph* graph, struct Stack* stack)
|
||||
// Transpose the adjacency list
|
||||
struct Graph *transpose(struct Graph *g)
|
||||
{
|
||||
struct Graph* graph = createGraph(g->numVertices);//Number of vertices is same
|
||||
struct Graph *graph =
|
||||
createGraph(g->numVertices); // Number of vertices is same
|
||||
int i = 0;
|
||||
for (i = 0; i < g->numVertices; i++)
|
||||
{
|
||||
@ -98,7 +103,8 @@ struct Graph* transpose(struct Graph* g)
|
||||
return graph;
|
||||
}
|
||||
// Recursive dfs aproach
|
||||
void dfs(struct Graph* graph, int vertex) {
|
||||
void dfs(struct Graph *graph, int vertex)
|
||||
{
|
||||
struct node *adjList = graph->adjLists[vertex];
|
||||
struct node *temp = adjList;
|
||||
|
||||
@ -107,9 +113,11 @@ void dfs(struct Graph* graph, int vertex) {
|
||||
printf("%d ", vertex);
|
||||
|
||||
// Recursively call the dfs function on all unvisited neighbours
|
||||
while(temp!=NULL) {
|
||||
while (temp != NULL)
|
||||
{
|
||||
int connectedVertex = temp->vertex;
|
||||
if(graph->visited[connectedVertex] == 0) {
|
||||
if (graph->visited[connectedVertex] == 0)
|
||||
{
|
||||
dfs(graph, connectedVertex);
|
||||
}
|
||||
temp = temp->next;
|
||||
@ -161,7 +169,8 @@ struct Graph* createGraph(int vertices)
|
||||
graph->visited = malloc(vertices * sizeof(int));
|
||||
|
||||
int i;
|
||||
for (i = 0; i < vertices; i++) {
|
||||
for (i = 0; i < vertices; i++)
|
||||
{
|
||||
graph->adjLists[i] = NULL;
|
||||
graph->visited[i] = 0;
|
||||
}
|
||||
@ -201,7 +210,8 @@ struct Stack* createStack()
|
||||
// Pushes element into stack
|
||||
void push(struct Stack *stack, int element)
|
||||
{
|
||||
stack->arr[++stack->top]=element;//Increment then add, as we start from -1
|
||||
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)
|
||||
|
@ -14,7 +14,9 @@ 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 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
|
||||
@ -69,9 +71,11 @@ void topologicalSortHelper(int vertex, struct Graph* graph, struct Stack* stack)
|
||||
struct node *adjList = graph->adjLists[vertex];
|
||||
struct node *temp = adjList;
|
||||
// First add all dependents (that is, children) to stack
|
||||
while(temp!=NULL) {
|
||||
while (temp != NULL)
|
||||
{
|
||||
int connectedVertex = temp->vertex;
|
||||
if(graph->visited[connectedVertex] == 0) {
|
||||
if (graph->visited[connectedVertex] == 0)
|
||||
{
|
||||
topologicalSortHelper(connectedVertex, graph, stack);
|
||||
}
|
||||
temp = temp->next;
|
||||
@ -113,7 +117,8 @@ struct Graph* createGraph(int vertices)
|
||||
graph->visited = malloc(vertices * sizeof(int));
|
||||
|
||||
int i;
|
||||
for (i = 0; i < vertices; i++) {
|
||||
for (i = 0; i < vertices; i++)
|
||||
{
|
||||
graph->adjLists[i] = NULL;
|
||||
graph->visited[i] = 0;
|
||||
}
|
||||
@ -153,7 +158,8 @@ struct Stack* createStack()
|
||||
// Pushes element into stack
|
||||
void push(struct Stack *stack, int element)
|
||||
{
|
||||
stack->arr[++stack->top]=element;//Increment then add, as we start from -1
|
||||
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)
|
||||
@ -163,4 +169,3 @@ int pop(struct Stack* stack)
|
||||
else
|
||||
return stack->arr[stack->top--];
|
||||
}
|
||||
|
||||
|
@ -1,12 +1,14 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define NODES 4
|
||||
|
||||
int digraph[NODES][NODES]={ {0,1,1,1}, {1,0,1,0}, {0,1,0,0}, {0,0,0,0} };
|
||||
int digraph[NODES][NODES] = {
|
||||
{0, 1, 1, 1}, {1, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0}};
|
||||
int tc[NODES][NODES];
|
||||
|
||||
void warshall() {
|
||||
void warshall()
|
||||
{
|
||||
int i, s, t;
|
||||
for (s = 0; s < NODES; s++)
|
||||
for (t = 0; t < NODES; t++)
|
||||
@ -19,11 +21,14 @@ void warshall() {
|
||||
tc[s][t] = 1;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int main(void)
|
||||
{
|
||||
warshall();
|
||||
int i, j;
|
||||
for (i = 0; i < NODES; i++) {
|
||||
for (j = 0; j < NODES; j++) {
|
||||
for (i = 0; i < NODES; i++)
|
||||
{
|
||||
for (j = 0; j < NODES; j++)
|
||||
{
|
||||
printf("%d ", tc[i][j]);
|
||||
}
|
||||
putchar('\n');
|
||||
@ -32,17 +37,25 @@ int main(void) {
|
||||
}
|
||||
|
||||
// By
|
||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
||||
// | | | || | | || | | || | | | | | | || | | |
|
||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
||||
// .----------------. .----------------. .----------------.
|
||||
// .-----------------. .----------------. .----------------.
|
||||
// | .--------------. || .--------------. || .--------------. ||
|
||||
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||
// | | | | | || | | || | | || | | | | |
|
||||
// | || | | | | '--------------' || '--------------' ||
|
||||
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||
// |
|
||||
// '----------------' '----------------' '----------------'
|
||||
// '----------------' '----------------' '----------------'
|
||||
|
||||
// Email : z5261243@unsw.edu.au
|
||||
// hhoanhtuann@gmail.com
|
||||
|
@ -21,8 +21,10 @@ unsigned add(hash_set_t *set, void *value)
|
||||
|
||||
unsigned put(hash_set_t *set, long long hash, void *value)
|
||||
{
|
||||
if (contains_hash(set, hash)) {
|
||||
if (set->keys[retrieve_index_from_hash(hash, set->capacity)] == value) {
|
||||
if (contains_hash(set, hash))
|
||||
{
|
||||
if (set->keys[retrieve_index_from_hash(hash, set->capacity)] == value)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -40,7 +42,10 @@ unsigned put(hash_set_t *set, long long hash, void *value)
|
||||
|
||||
int contains(hash_set_t *set, void *value)
|
||||
{
|
||||
return set->keys[retrieve_index_from_hash(hash(value), set->capacity)] == value ? 1 : 0;
|
||||
return set->keys[retrieve_index_from_hash(hash(value), set->capacity)] ==
|
||||
value
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
|
||||
int contains_hash(hash_set_t *set, long long hash)
|
||||
@ -48,11 +53,11 @@ int contains_hash(hash_set_t *set, long long hash)
|
||||
return set->keys[retrieve_index_from_hash(hash, set->capacity)] ? 1 : 0;
|
||||
}
|
||||
|
||||
void delete(hash_set_t *set, void *value) {
|
||||
void delete (hash_set_t *set, void *value)
|
||||
{
|
||||
set->keys[retrieve_index_from_hash(hash(value), set->capacity)] = NULL;
|
||||
}
|
||||
|
||||
|
||||
// adler_32 hash
|
||||
long long hash(void *value)
|
||||
{
|
||||
@ -62,7 +67,8 @@ long long hash(void *value)
|
||||
int b = 0;
|
||||
const int MODADLER = 65521;
|
||||
|
||||
for (int i = 0; str[i] != '\0'; i++) {
|
||||
for (int i = 0; str[i] != '\0'; i++)
|
||||
{
|
||||
a = (a + str[i]) % MODADLER;
|
||||
b = (b + a) % MODADLER;
|
||||
}
|
||||
@ -79,14 +85,17 @@ void resize(hash_set_t *set)
|
||||
{
|
||||
void **keys_resized = calloc((set->capacity <<= 1), sizeof(void **));
|
||||
|
||||
for (int i = 0; i < set->length; i++) {
|
||||
keys_resized[retrieve_index_from_hash(hash(set->values[i]), set->capacity)] = set->values[i];
|
||||
for (int i = 0; i < set->length; i++)
|
||||
{
|
||||
keys_resized[retrieve_index_from_hash(hash(set->values[i]),
|
||||
set->capacity)] = set->values[i];
|
||||
}
|
||||
|
||||
free(set->keys);
|
||||
|
||||
set->keys = keys_resized;
|
||||
|
||||
void **new_values = (void **)realloc(set->values, set->capacity * sizeof(void **));
|
||||
void **new_values =
|
||||
(void **)realloc(set->values, set->capacity * sizeof(void **));
|
||||
set->values = new_values;
|
||||
}
|
||||
|
@ -3,7 +3,8 @@
|
||||
|
||||
#define DEFAULT_HASH_SET_CAPACITY 1 << 10
|
||||
|
||||
typedef struct {
|
||||
typedef struct
|
||||
{
|
||||
unsigned capacity;
|
||||
unsigned length;
|
||||
void **values;
|
||||
@ -24,7 +25,8 @@ extern void delete(hash_set_t *set, void *value);
|
||||
|
||||
extern long long hash(void *value);
|
||||
|
||||
extern unsigned retrieve_index_from_hash(const long long hash, const unsigned capacity);
|
||||
extern unsigned retrieve_index_from_hash(const long long hash,
|
||||
const unsigned capacity);
|
||||
|
||||
extern void resize(hash_set_t *set);
|
||||
|
||||
|
@ -1,22 +1,28 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct max_heap{
|
||||
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*/
|
||||
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 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(){
|
||||
int main()
|
||||
{
|
||||
Heap *head = create_heap(head);
|
||||
push(head, 10);
|
||||
printf("Pushing element : 10\n");
|
||||
@ -41,7 +47,8 @@ int main(){
|
||||
printf("\n");
|
||||
return 0;
|
||||
}
|
||||
Heap* create_heap(Heap* heap){
|
||||
Heap *create_heap(Heap *heap)
|
||||
{
|
||||
heap = (Heap *)malloc(sizeof(Heap));
|
||||
heap->size = 1;
|
||||
heap->p = (int *)malloc(heap->size * sizeof(int));
|
||||
@ -49,37 +56,46 @@ Heap* create_heap(Heap* heap){
|
||||
return heap;
|
||||
}
|
||||
|
||||
void down_heapify(Heap* heap, int index){
|
||||
if(index>=heap->count)return;
|
||||
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)){
|
||||
if (left < heap->count && maximum < *((heap->p) + left))
|
||||
{
|
||||
maximum = *((heap->p) + left);
|
||||
leftflag = 1;
|
||||
}
|
||||
if(right<heap->count && maximum<*((heap->p)+right)){
|
||||
if (right < heap->count && maximum < *((heap->p) + right))
|
||||
{
|
||||
maximum = *((heap->p) + right);
|
||||
leftflag = 0;
|
||||
rightflag = 1;
|
||||
}
|
||||
if(leftflag){
|
||||
if (leftflag)
|
||||
{
|
||||
*((heap->p) + left) = *((heap->p) + index);
|
||||
*((heap->p) + index) = maximum;
|
||||
down_heapify(heap, left);
|
||||
}
|
||||
if(rightflag){
|
||||
if (rightflag)
|
||||
{
|
||||
*((heap->p) + right) = *((heap->p) + index);
|
||||
*((heap->p) + index) = maximum;
|
||||
down_heapify(heap, right);
|
||||
}
|
||||
}
|
||||
void up_heapify(Heap* heap, int index){
|
||||
void up_heapify(Heap *heap, int index)
|
||||
{
|
||||
int parent = (index - 1) / 2;
|
||||
if(parent<0)return;
|
||||
if(*((heap->p)+index)>*((heap->p)+parent)){
|
||||
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;
|
||||
@ -87,36 +103,46 @@ void up_heapify(Heap* heap, int index){
|
||||
}
|
||||
}
|
||||
|
||||
void push(Heap* heap, int x){
|
||||
if(heap->count>=heap->size)return;
|
||||
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){
|
||||
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;
|
||||
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){
|
||||
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 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;
|
||||
int empty(Heap *heap)
|
||||
{
|
||||
if (heap->count != 0)
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
int size(Heap *heap) { return heap->count; }
|
||||
|
@ -1,22 +1,28 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct min_heap{
|
||||
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*/
|
||||
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 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(){
|
||||
int main()
|
||||
{
|
||||
Heap *head = create_heap(head);
|
||||
push(head, 10);
|
||||
printf("Pushing element : 10\n");
|
||||
@ -41,7 +47,8 @@ int main(){
|
||||
printf("\n");
|
||||
return 0;
|
||||
}
|
||||
Heap* create_heap(Heap* heap){
|
||||
Heap *create_heap(Heap *heap)
|
||||
{
|
||||
heap = (Heap *)malloc(sizeof(Heap));
|
||||
heap->size = 1;
|
||||
heap->p = (int *)malloc(heap->size * sizeof(int));
|
||||
@ -49,37 +56,46 @@ Heap* create_heap(Heap* heap){
|
||||
return heap;
|
||||
}
|
||||
|
||||
void down_heapify(Heap* heap, int index){
|
||||
if(index>=heap->count)return;
|
||||
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)){
|
||||
if (left < heap->count && minimum > *((heap->p) + left))
|
||||
{
|
||||
minimum = *((heap->p) + left);
|
||||
leftflag = 1;
|
||||
}
|
||||
if(right<heap->count && minimum>*((heap->p)+right)){
|
||||
if (right < heap->count && minimum > *((heap->p) + right))
|
||||
{
|
||||
minimum = *((heap->p) + right);
|
||||
leftflag = 0;
|
||||
rightflag = 1;
|
||||
}
|
||||
if(leftflag){
|
||||
if (leftflag)
|
||||
{
|
||||
*((heap->p) + left) = *((heap->p) + index);
|
||||
*((heap->p) + index) = minimum;
|
||||
down_heapify(heap, left);
|
||||
}
|
||||
if(rightflag){
|
||||
if (rightflag)
|
||||
{
|
||||
*((heap->p) + right) = *((heap->p) + index);
|
||||
*((heap->p) + index) = minimum;
|
||||
down_heapify(heap, right);
|
||||
}
|
||||
}
|
||||
void up_heapify(Heap* heap, int index){
|
||||
void up_heapify(Heap *heap, int index)
|
||||
{
|
||||
int parent = (index - 1) / 2;
|
||||
if(parent<0)return;
|
||||
if(*((heap->p)+index)<*((heap->p)+parent)){
|
||||
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;
|
||||
@ -87,36 +103,46 @@ void up_heapify(Heap* heap, int index){
|
||||
}
|
||||
}
|
||||
|
||||
void push(Heap* heap, int x){
|
||||
if(heap->count>=heap->size)return;
|
||||
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){
|
||||
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;
|
||||
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){
|
||||
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 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;
|
||||
int empty(Heap *heap)
|
||||
{
|
||||
if (heap->count != 0)
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
int size(Heap *heap) { return heap->count; }
|
||||
|
@ -1,22 +1,27 @@
|
||||
/* Ascending priority queue using Linked List - Program to implement Ascending priority queue using Linked List */
|
||||
/* Ascending priority queue using Linked List - Program to implement Ascending
|
||||
* priority queue using Linked List */
|
||||
|
||||
/*A priority queue is a special type of queue in which each element is associated with a priority and is served according
|
||||
to its priority. If elements with the same priority occur, they are served according to their order in the queue.
|
||||
/*A priority queue is a special type of queue in which each element is
|
||||
associated with a priority and is served according to its priority. If elements
|
||||
with the same priority occur, they are served according to their order in the
|
||||
queue.
|
||||
|
||||
Generally, the value of the element itself is considered for assigning the priority.
|
||||
Generally, the value of the element itself is considered for assigning the
|
||||
priority.
|
||||
|
||||
For example: The element with the highest value is considered as the highest priority element. However, in other cases,
|
||||
we can assume the element with the lowest value as the highest priority element. In other cases,
|
||||
we can set priorities according to our needs.
|
||||
For example: The element with the highest value is considered as the highest
|
||||
priority element. However, in other cases, we can assume the element with the
|
||||
lowest value as the highest priority element. In other cases, we can set
|
||||
priorities according to our needs.
|
||||
|
||||
In a queue, the first-in-first-out rule is implemented whereas, in a priority queue, the values are removed on the basis of priority.
|
||||
The element with the highest priority is removed first.
|
||||
In a queue, the first-in-first-out rule is implemented whereas, in a priority
|
||||
queue, the values are removed on the basis of priority. The element with the
|
||||
highest priority is removed first.
|
||||
|
||||
insert() - Would insert an element in a queue
|
||||
delete() - Would delete the smallest element in the queue
|
||||
*/
|
||||
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#define NULL ((void *)0)
|
||||
@ -29,11 +34,9 @@ struct node
|
||||
|
||||
struct node *front, *rear;
|
||||
|
||||
/* This function initializes the queue to empty by making both front and rear as NULL */
|
||||
void createqueue()
|
||||
{
|
||||
front=rear=NULL ;
|
||||
}
|
||||
/* This function initializes the queue to empty by making both front and rear as
|
||||
* NULL */
|
||||
void createqueue() { front = rear = NULL; }
|
||||
|
||||
int empty()
|
||||
{
|
||||
@ -109,7 +112,6 @@ int removes()
|
||||
else /* deleting any other node.*/
|
||||
follow1->next = p1->next;
|
||||
|
||||
|
||||
free(p1);
|
||||
return min; /* DONT FORGET LAST 2 STATEMENTS.*/
|
||||
}
|
||||
@ -135,10 +137,7 @@ void show()
|
||||
}
|
||||
}
|
||||
|
||||
void destroyqueue()
|
||||
{
|
||||
front=rear=NULL ;
|
||||
}
|
||||
void destroyqueue() { front = rear = NULL; }
|
||||
|
||||
int main()
|
||||
{
|
||||
@ -146,7 +145,6 @@ int main()
|
||||
|
||||
createqueue();
|
||||
|
||||
|
||||
do
|
||||
{
|
||||
printf("\n\n Menu: \n");
|
||||
@ -174,8 +172,7 @@ int main()
|
||||
case 3:
|
||||
break;
|
||||
}
|
||||
}
|
||||
while(ch!=3) ;
|
||||
} while (ch != 3);
|
||||
|
||||
destroyqueue();
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
struct node{
|
||||
struct node
|
||||
{
|
||||
int data;
|
||||
struct node *next;
|
||||
};
|
||||
@ -17,30 +18,37 @@ void merge()
|
||||
|
||||
struct node *holder1 = NULL;
|
||||
struct node *holder2 = NULL;
|
||||
//Temporary pointer variables to store the address of next node of the two input linked list
|
||||
// Temporary pointer variables to store the address of next node of the two
|
||||
// input linked list
|
||||
|
||||
while (temp1 != NULL && temp2 != NULL)
|
||||
{
|
||||
holder1 = temp1->next;
|
||||
// Storing the address of next node of first linked list
|
||||
temp1->next = temp2;
|
||||
//Making the first node of first linked list point to first node of second linked list
|
||||
// Making the first node of first linked list point to first node of
|
||||
// second linked list
|
||||
|
||||
if(holder1!=NULL) {
|
||||
//Making the first node of second linked list point to second node of first linked list
|
||||
if (holder1 != NULL)
|
||||
{
|
||||
// Making the first node of second linked list point to second node
|
||||
// of first linked list
|
||||
holder2 = temp2->next;
|
||||
temp2->next = holder1;
|
||||
}
|
||||
temp1 = holder1;
|
||||
temp2 = holder2;
|
||||
//Updating the address location of two pointer variables temp1 and temp2
|
||||
// Updating the address location of two pointer variables temp1 and
|
||||
// temp2
|
||||
}
|
||||
}
|
||||
|
||||
void printlist(struct node *temp){
|
||||
void printlist(struct node *temp)
|
||||
{
|
||||
printf("%d", temp->data);
|
||||
temp = temp->next;
|
||||
while(temp!=NULL){
|
||||
while (temp != NULL)
|
||||
{
|
||||
printf("->%d", temp->data);
|
||||
temp = temp->next;
|
||||
}
|
||||
|
@ -28,8 +28,7 @@ void printMiddle(struct Node *head)
|
||||
void push(struct Node **head_ref, int new_data)
|
||||
{
|
||||
/* allocate node */
|
||||
struct Node* new_node =
|
||||
(struct Node*) malloc(sizeof(struct Node));
|
||||
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
|
||||
|
||||
/* put in the data */
|
||||
new_node->data = new_data;
|
||||
|
@ -1,8 +1,6 @@
|
||||
/* Queue using Linked List - Program to create a queue ADT using linked list. ADT should support the following operations
|
||||
1) Createqueue
|
||||
2) Insert into the queue
|
||||
3) Delete from the queue
|
||||
4) destroyqueue
|
||||
/* Queue using Linked List - Program to create a queue ADT using linked list.
|
||||
ADT should support the following operations 1) Createqueue 2) Insert into the
|
||||
queue 3) Delete from the queue 4) destroyqueue
|
||||
*/
|
||||
|
||||
/* queue q declared globally */
|
||||
@ -24,11 +22,9 @@ struct queue
|
||||
|
||||
struct queue q;
|
||||
|
||||
/* This function initializes the queue to empty by making both front and rear as NULL */
|
||||
void createqueue()
|
||||
{
|
||||
q.front=q.rear=NULL ;
|
||||
}
|
||||
/* This function initializes the queue to empty by making both front and rear as
|
||||
* NULL */
|
||||
void createqueue() { q.front = q.rear = NULL; }
|
||||
|
||||
int empty()
|
||||
{
|
||||
@ -102,10 +98,7 @@ void show()
|
||||
}
|
||||
}
|
||||
|
||||
void destroyqueue()
|
||||
{
|
||||
q.front=q.rear=NULL ;
|
||||
}
|
||||
void destroyqueue() { q.front = q.rear = NULL; }
|
||||
|
||||
int main()
|
||||
{
|
||||
@ -140,8 +133,7 @@ int main()
|
||||
case 3:
|
||||
break;
|
||||
}
|
||||
}
|
||||
while(ch!=3) ;
|
||||
} while (ch != 3);
|
||||
|
||||
destroyqueue();
|
||||
|
||||
|
@ -1,11 +1,12 @@
|
||||
/*Includes structure for a node which can be use to make new nodes of the Linked List.
|
||||
It is assumed that the data in nodes will be an integer, though
|
||||
function can be modified according to the data type, easily.
|
||||
deleteNode deletes a node when passed with a key of the node.
|
||||
/*Includes structure for a node which can be use to make new nodes of the Linked
|
||||
List. It is assumed that the data in nodes will be an integer, though function
|
||||
can be modified according to the data type, easily. deleteNode deletes a node
|
||||
when passed with a key of the node.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
struct node
|
||||
{int info;
|
||||
{
|
||||
int info;
|
||||
struct node *link;
|
||||
};
|
||||
struct node *start = NULL;
|
||||
@ -59,7 +60,8 @@ void viewlist()//function to display values
|
||||
printf("\nlist is empty");
|
||||
}
|
||||
else
|
||||
{ p=start;
|
||||
{
|
||||
p = start;
|
||||
while (p != NULL)
|
||||
{
|
||||
printf("%d ", p->info);
|
||||
|
@ -24,15 +24,16 @@ int main()
|
||||
case 1:
|
||||
push(top);
|
||||
break;
|
||||
case 2: pop(top);
|
||||
case 2:
|
||||
pop(top);
|
||||
break;
|
||||
case 3: display(top);
|
||||
case 3:
|
||||
display(top);
|
||||
break;
|
||||
case 4: return 0;
|
||||
|
||||
case 4:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void push(struct node *p)
|
||||
@ -44,13 +45,9 @@ void push(struct node *p)
|
||||
scanf("%d", &item);
|
||||
temp->info = item;
|
||||
|
||||
|
||||
|
||||
temp->link = top;
|
||||
top = temp;
|
||||
|
||||
|
||||
|
||||
printf("inserted succesfully\n");
|
||||
}
|
||||
void pop(struct node *p)
|
||||
@ -60,33 +57,29 @@ void pop(struct node *p)
|
||||
|
||||
if (top == NULL)
|
||||
printf("stack is empty\n");
|
||||
else{
|
||||
else
|
||||
{
|
||||
item = top->info;
|
||||
temp = top;
|
||||
top = top->link;
|
||||
free(temp);
|
||||
printf("Element popped is%d\n", item);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
void display(struct node *p)
|
||||
{
|
||||
|
||||
if (top == NULL)
|
||||
printf("stack is empty\n");
|
||||
else
|
||||
{ printf("Elements in the stack are\n");
|
||||
{
|
||||
printf("Elements in the stack are\n");
|
||||
while (p != NULL)
|
||||
{
|
||||
printf("%d\n", p->info);
|
||||
p = p->link;
|
||||
}
|
||||
// printf("%d\n",p->info);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,14 +1,15 @@
|
||||
#include "list.h"
|
||||
#include <assert.h>
|
||||
#include <stdarg.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_init(void)
|
||||
{
|
||||
L list;
|
||||
list = (L)malloc(sizeof(L));
|
||||
list->next = NULL;
|
||||
@ -16,7 +17,8 @@ L List_init (void) {
|
||||
}
|
||||
|
||||
/* Push an element into top of the list */
|
||||
L List_push(L list, void *val) {
|
||||
L List_push(L list, void *val)
|
||||
{
|
||||
L new_elem = (L)malloc(sizeof(L));
|
||||
new_elem->val = val;
|
||||
new_elem->next = list;
|
||||
@ -24,7 +26,8 @@ L List_push(L list, void *val) {
|
||||
}
|
||||
|
||||
/* Length of list */
|
||||
int List_length(L list) {
|
||||
int List_length(L list)
|
||||
{
|
||||
int n;
|
||||
for (n = 0; list; list = list->next)
|
||||
n++;
|
||||
@ -32,11 +35,13 @@ int List_length(L list) {
|
||||
}
|
||||
|
||||
/* Convert list to array */
|
||||
void **List_toArray(L list) {
|
||||
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++) {
|
||||
for (i = 0; i < n; i++)
|
||||
{
|
||||
array[i] = list->val;
|
||||
list = list->next;
|
||||
}
|
||||
@ -45,12 +50,14 @@ void **List_toArray(L list) {
|
||||
}
|
||||
|
||||
/* Create and return a list */
|
||||
L List_list(L list, void *val, ...) {
|
||||
L List_list(L list, void *val, ...)
|
||||
{
|
||||
va_list ap;
|
||||
L *p = &list;
|
||||
|
||||
va_start(ap, val);
|
||||
for(; val; val = va_arg(ap, void *)) {
|
||||
for (; val; val = va_arg(ap, void *))
|
||||
{
|
||||
*p = malloc(sizeof(L));
|
||||
(*p)->val = val;
|
||||
p = &(*p)->next;
|
||||
@ -61,13 +68,14 @@ L List_list(L list, void *val, ...) {
|
||||
}
|
||||
|
||||
/* Append 2 lists together */
|
||||
L List_append(L list, L tail) {
|
||||
L List_append(L list, L tail)
|
||||
{
|
||||
L *p = &list;
|
||||
while((*p)->next) {
|
||||
while ((*p)->next)
|
||||
{
|
||||
p = &(*p)->next;
|
||||
}
|
||||
|
||||
*p = tail;
|
||||
return list;
|
||||
}
|
||||
|
||||
|
@ -4,7 +4,8 @@
|
||||
#define L List_T
|
||||
typedef struct L *L;
|
||||
|
||||
struct L {
|
||||
struct L
|
||||
{
|
||||
void *val;
|
||||
L next;
|
||||
};
|
||||
|
@ -1,17 +1,19 @@
|
||||
#include "list.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#include "list.h"
|
||||
|
||||
void print_list(char **array) {
|
||||
void print_list(char **array)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; array[i]; i++)
|
||||
printf("%s", array[i]);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
List_T list1, list2, list3;
|
||||
char **str1 = (char **)malloc(100 * sizeof(char *));
|
||||
|
||||
|
@ -8,7 +8,8 @@
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// DATA STRUCTURES
|
||||
struct node {
|
||||
struct node
|
||||
{
|
||||
int data;
|
||||
struct node *next;
|
||||
struct node *pre;
|
||||
@ -30,17 +31,17 @@ int isEmpty();
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// MAIN ENTRY POINT
|
||||
|
||||
int main(int argc, char const *argv[]) {
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
|
||||
create();
|
||||
enque(5);
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
void create() {
|
||||
void create()
|
||||
{
|
||||
head = NULL;
|
||||
tail = NULL;
|
||||
}
|
||||
@ -48,13 +49,17 @@ void create() {
|
||||
/**
|
||||
* Puts an item into the Queue.
|
||||
*/
|
||||
void enque(int x) {
|
||||
if(head == NULL) {
|
||||
void enque(int x)
|
||||
{
|
||||
if (head == NULL)
|
||||
{
|
||||
head = (struct node *)malloc(1 * sizeof(struct node));
|
||||
head->data = x;
|
||||
head->pre = NULL;
|
||||
tail = head;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
tmp = (struct node *)malloc(1 * sizeof(struct node));
|
||||
tmp->data = x;
|
||||
tmp->next = tail;
|
||||
@ -65,12 +70,16 @@ void enque(int x) {
|
||||
/**
|
||||
* Takes the next item from the Queue.
|
||||
*/
|
||||
int deque() {
|
||||
int deque()
|
||||
{
|
||||
int returnData = 0;
|
||||
if(head == NULL) {
|
||||
if (head == NULL)
|
||||
{
|
||||
printf("ERROR: Deque from empty queue.\n");
|
||||
exit(1);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
returnData = head->data;
|
||||
if (head->pre == NULL)
|
||||
head = NULL;
|
||||
@ -84,6 +93,4 @@ int deque() {
|
||||
/**
|
||||
* Returns the size of the Queue.
|
||||
*/
|
||||
int size() {
|
||||
return count;
|
||||
}
|
||||
int size() { return count; }
|
@ -13,7 +13,8 @@
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// DATA STRUCTURES
|
||||
struct node {
|
||||
struct node
|
||||
{
|
||||
int data;
|
||||
struct node *next;
|
||||
struct node *pre;
|
||||
@ -35,7 +36,8 @@ int isEmpty();
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// MAIN ENTRY POINT
|
||||
|
||||
int main(int argc, char const *argv[]) {
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
|
||||
int x, y, z;
|
||||
|
||||
@ -70,20 +72,22 @@ int main(int argc, char const *argv[]) {
|
||||
/**
|
||||
* Initialize the stack to NULL.
|
||||
*/
|
||||
void create() {
|
||||
head = NULL;
|
||||
}
|
||||
void create() { head = NULL; }
|
||||
|
||||
/**
|
||||
* Push data onto the stack.
|
||||
*/
|
||||
void push(int x) {
|
||||
if(head == NULL) {
|
||||
void push(int x)
|
||||
{
|
||||
if (head == NULL)
|
||||
{
|
||||
head = (struct node *)malloc(1 * sizeof(struct node));
|
||||
head->next = NULL;
|
||||
head->pre = NULL;
|
||||
head->data = x;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
tmp = (struct node *)malloc(1 * sizeof(struct node));
|
||||
tmp->data = x;
|
||||
tmp->next = NULL;
|
||||
@ -97,19 +101,25 @@ void push(int x) {
|
||||
/**
|
||||
* Pop data from the stack
|
||||
*/
|
||||
int pop() {
|
||||
int pop()
|
||||
{
|
||||
int returnData;
|
||||
if(head == NULL) {
|
||||
if (head == NULL)
|
||||
{
|
||||
printf("ERROR: Pop from empty stack.\n");
|
||||
exit(1);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
returnData = head->data;
|
||||
|
||||
if(head->pre == NULL){
|
||||
if (head->pre == NULL)
|
||||
{
|
||||
free(head);
|
||||
head = NULL;
|
||||
}
|
||||
else {
|
||||
else
|
||||
{
|
||||
head = head->pre;
|
||||
free(head->next);
|
||||
}
|
||||
@ -121,10 +131,12 @@ int pop() {
|
||||
/**
|
||||
* Returns the next value to be popped.
|
||||
*/
|
||||
int peek() {
|
||||
int peek()
|
||||
{
|
||||
if (head != NULL)
|
||||
return head->data;
|
||||
else {
|
||||
else
|
||||
{
|
||||
printf("ERROR: Peeking from empty stack.");
|
||||
exit(1);
|
||||
}
|
||||
@ -133,14 +145,13 @@ int peek() {
|
||||
/**
|
||||
* Returns the size of the stack.
|
||||
*/
|
||||
int size() {
|
||||
return count;
|
||||
}
|
||||
int size() { return count; }
|
||||
|
||||
/**
|
||||
* Returns 1 if stack is empty, returns 0 if not empty.
|
||||
*/
|
||||
int isEmpty() {
|
||||
int isEmpty()
|
||||
{
|
||||
if (count == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
|
@ -1,7 +1,7 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
|
||||
#define SIZE 100
|
||||
|
||||
@ -19,7 +19,8 @@ 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
|
||||
if (head ==
|
||||
NULL) // will be execute only one time i.e, 1st time push is called
|
||||
{
|
||||
head = temp;
|
||||
p = head;
|
||||
@ -53,11 +54,13 @@ int isBalanced(char *s)
|
||||
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
|
||||
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
|
||||
if (c <= 0) // i.e, stack is empty as only opening brackets are
|
||||
// added to stack
|
||||
return 0;
|
||||
|
||||
x = pop();
|
||||
@ -71,7 +74,8 @@ int isBalanced(char *s)
|
||||
i++;
|
||||
}
|
||||
|
||||
//at end if stack is empy which means whole process has been performed correctly so return 1
|
||||
// at end if stack is empy which means whole process has been performed
|
||||
// correctly so return 1
|
||||
return (c == 0) ? 1 : 0;
|
||||
}
|
||||
|
||||
|
@ -6,9 +6,9 @@
|
||||
of data hiding.
|
||||
*/
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include "stack.h"
|
||||
|
||||
@ -114,18 +114,12 @@ void *pop()
|
||||
/*
|
||||
size: gets the number of elements of the stack.
|
||||
*/
|
||||
int size()
|
||||
{
|
||||
return counter;
|
||||
}
|
||||
int size() { return counter; }
|
||||
|
||||
/*
|
||||
isEmpty(): returns 1 if stack is empty otherwise 0.
|
||||
*/
|
||||
int isEmpty()
|
||||
{
|
||||
return counter == 0;
|
||||
}
|
||||
int isEmpty() { return counter == 0; }
|
||||
|
||||
/*
|
||||
top: returns the top element from the stack without removing it.
|
||||
|
@ -5,7 +5,6 @@
|
||||
The stack is generic and self growing.
|
||||
*/
|
||||
|
||||
|
||||
#ifndef __STACK__
|
||||
#define __STACK__
|
||||
|
||||
|
@ -1,9 +1,10 @@
|
||||
#include "stack.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include "stack.h"
|
||||
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
Stack_T stk;
|
||||
stk = Stack_init();
|
||||
Stack_push(stk, (int *)1);
|
||||
|
@ -1,23 +1,26 @@
|
||||
#include "stack.h"
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include "stack.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
#define T Stack_T
|
||||
|
||||
typedef struct elem {
|
||||
typedef struct elem
|
||||
{
|
||||
void *val;
|
||||
struct elem *next;
|
||||
} elem_t;
|
||||
|
||||
struct T {
|
||||
struct T
|
||||
{
|
||||
int count;
|
||||
elem_t *head;
|
||||
};
|
||||
|
||||
/* Initial stack */
|
||||
T Stack_init (void) {
|
||||
T Stack_init(void)
|
||||
{
|
||||
T stack;
|
||||
stack = (T)malloc(sizeof(T));
|
||||
stack->count = 0;
|
||||
@ -26,19 +29,22 @@ T Stack_init (void) {
|
||||
}
|
||||
|
||||
/* Check empty stack*/
|
||||
int Stack_empty(T stack) {
|
||||
int Stack_empty(T stack)
|
||||
{
|
||||
assert(stack);
|
||||
return stack->count == 0;
|
||||
}
|
||||
|
||||
/* Return size of the stack */
|
||||
int Stack_size(T stack) {
|
||||
int Stack_size(T stack)
|
||||
{
|
||||
assert(stack);
|
||||
return stack->count;
|
||||
}
|
||||
|
||||
/* Push an element into the stack */
|
||||
void Stack_push(T stack, void *val) {
|
||||
void Stack_push(T stack, void *val)
|
||||
{
|
||||
elem_t *t;
|
||||
|
||||
assert(stack);
|
||||
@ -50,7 +56,8 @@ void Stack_push(T stack, void *val) {
|
||||
}
|
||||
|
||||
/* Pop an element out of the stack */
|
||||
void *Stack_pop(T stack) {
|
||||
void *Stack_pop(T stack)
|
||||
{
|
||||
void *val;
|
||||
elem_t *t;
|
||||
|
||||
@ -65,13 +72,15 @@ void *Stack_pop(T stack) {
|
||||
}
|
||||
|
||||
/* Print all elements in the stack */
|
||||
void Stack_print(Stack_T 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) {
|
||||
for (i = 0; i < size; ++i)
|
||||
{
|
||||
printf("%p ", (int *)current_elem->val);
|
||||
current_elem = current_elem->next;
|
||||
}
|
||||
|
@ -3,8 +3,8 @@
|
||||
|
||||
/*-----character - 97 used for get the character from the ASCII value-----*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
@ -26,7 +26,8 @@ TrieNode *createTrieNode()
|
||||
node = malloc(sizeof(TrieNode));
|
||||
node->isEndOfWord = false;
|
||||
int i = 0;
|
||||
while(i<ALPHABET_SIZE){
|
||||
while (i < ALPHABET_SIZE)
|
||||
{
|
||||
node->children[i] = NULL;
|
||||
i++;
|
||||
}
|
||||
@ -95,7 +96,8 @@ void printArray(char chars[], int len)
|
||||
/*---Return all the related words------*/
|
||||
void printPathsRecur(TrieNode *node, char prefix[], int filledLen)
|
||||
{
|
||||
if (node==NULL) return;
|
||||
if (node == NULL)
|
||||
return;
|
||||
|
||||
prefix[filledLen] = node->character;
|
||||
filledLen++;
|
||||
@ -158,7 +160,6 @@ int main()
|
||||
words[word_count] = malloc(INPUT_WORD_SIZE);
|
||||
}
|
||||
|
||||
|
||||
// Push the words in to Trie
|
||||
TrieNode *root = NULL;
|
||||
root = createTrieNode();
|
||||
@ -173,12 +174,14 @@ int main()
|
||||
printf("Enter keyword: ");
|
||||
char str[100];
|
||||
receiveInput(str);
|
||||
printf("\n==========================================================\n");
|
||||
printf(
|
||||
"\n==========================================================\n");
|
||||
printf("\n********************* Possible Words ********************\n");
|
||||
|
||||
// Find the word through the Trie
|
||||
traverse(str, root);
|
||||
|
||||
printf("\n==========================================================\n");
|
||||
printf(
|
||||
"\n==========================================================\n");
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
char *abbreviate(const char *phrase)
|
||||
{
|
||||
|
@ -5,7 +5,8 @@
|
||||
#define MAX_WORD_LENGTH 50 // no individual word can exceed this length
|
||||
|
||||
// results structure
|
||||
typedef struct word_count_word {
|
||||
typedef struct word_count_word
|
||||
{
|
||||
char text[MAX_WORD_LENGTH];
|
||||
int count;
|
||||
} word_count_word_t;
|
||||
@ -13,8 +14,8 @@ typedef struct word_count_word {
|
||||
#define EXCESSIVE_LENGTH_WORD -1
|
||||
#define EXCESSIVE_NUMBER_OF_WORDS -2
|
||||
|
||||
// word_count - routine to classify the unique words and their frequency in a test input string
|
||||
// inputs:
|
||||
// word_count - routine to classify the unique words and their frequency in a
|
||||
// test input string inputs:
|
||||
// input_text = a null-terminated string containing that is analyzed
|
||||
//
|
||||
// outputs:
|
||||
|
@ -12,43 +12,48 @@ int dist[MAX];
|
||||
int q[MAX];
|
||||
int qp = 0;
|
||||
|
||||
void enqueue (int v) {
|
||||
q[qp++] = v;
|
||||
}
|
||||
void enqueue(int v) { q[qp++] = v; }
|
||||
|
||||
int cf (void *a, void *b) {
|
||||
int cf(void *a, void *b)
|
||||
{
|
||||
int *x = (int *)a;
|
||||
int *y = (int *)b;
|
||||
return *y - *x;
|
||||
}
|
||||
|
||||
int dequeue () {
|
||||
int dequeue()
|
||||
{
|
||||
qsort(q, qp, sizeof(int), cf);
|
||||
return q[--qp];
|
||||
}
|
||||
|
||||
int queue_has_something () {
|
||||
return (qp > 0);
|
||||
}
|
||||
int queue_has_something() { return (qp > 0); }
|
||||
|
||||
int visited[MAX];
|
||||
int vp = 0;
|
||||
|
||||
void dijkstra (int s) {
|
||||
void dijkstra(int s)
|
||||
{
|
||||
dist[s] = 0;
|
||||
int i;
|
||||
for (i = 0; i < V; ++i) {
|
||||
if (i != s) {
|
||||
for (i = 0; i < V; ++i)
|
||||
{
|
||||
if (i != s)
|
||||
{
|
||||
dist[i] = INF;
|
||||
}
|
||||
enqueue(i);
|
||||
}
|
||||
while (queue_has_something()) {
|
||||
while (queue_has_something())
|
||||
{
|
||||
int u = dequeue();
|
||||
visited[vp++] = u;
|
||||
for (i = 0; i < V; ++i) {
|
||||
if (mat[u][i]) {
|
||||
if (dist[i] > dist[u] + mat[u][i]) {
|
||||
for (i = 0; i < V; ++i)
|
||||
{
|
||||
if (mat[u][i])
|
||||
{
|
||||
if (dist[i] > dist[u] + mat[u][i])
|
||||
{
|
||||
dist[i] = dist[u] + mat[u][i];
|
||||
}
|
||||
}
|
||||
@ -56,14 +61,17 @@ void dijkstra (int s) {
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char const *argv[]) {
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
|
||||
printf("Enter the number of vertices: ");
|
||||
scanf(" %d", &V);
|
||||
printf("Enter the adj matrix: ");
|
||||
int i, j;
|
||||
for (i = 0; i < V; ++i) {
|
||||
for (j = 0; j < V; ++j) {
|
||||
for (i = 0; i < V; ++i)
|
||||
{
|
||||
for (j = 0; j < V; ++j)
|
||||
{
|
||||
scanf(" %d", &mat[i][j]);
|
||||
}
|
||||
}
|
||||
@ -71,7 +79,8 @@ int main(int argc, char const *argv[]) {
|
||||
dijkstra(0);
|
||||
|
||||
printf("\nNode\tDist\n");
|
||||
for (i = 0; i < V; ++i) {
|
||||
for (i = 0; i < V; ++i)
|
||||
{
|
||||
printf("%d\t%d\n", i, dist[i]);
|
||||
}
|
||||
|
||||
|
@ -65,10 +65,12 @@ int adler_32(char s[])
|
||||
/* crc32 Hash-Algorithm*/
|
||||
#include <inttypes.h>
|
||||
|
||||
uint32_t crc32(char* data){
|
||||
uint32_t crc32(char *data)
|
||||
{
|
||||
int i = 0;
|
||||
uint32_t crc = 0xffffffff;
|
||||
while(data[i] != '\0'){
|
||||
while (data[i] != '\0')
|
||||
{
|
||||
uint8_t byte = data[i];
|
||||
crc = crc ^ byte;
|
||||
for (int j = 8; j > 0; --j)
|
||||
|
@ -46,6 +46,4 @@ int adler_32(char[]);
|
||||
*/
|
||||
int crc32(char[]);
|
||||
|
||||
|
||||
|
||||
#endif
|
@ -3,8 +3,8 @@
|
||||
This file contains a simple test program for each hash-function.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "hash.h"
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
|
@ -1,10 +1,13 @@
|
||||
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
|
||||
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++) {
|
||||
for (i = 0; i < numsSize; i++)
|
||||
{
|
||||
int key = target - nums[i];
|
||||
for (j = i + 1; j < numsSize; j++)
|
||||
if (nums[j] == key) {
|
||||
if (nums[j] == key)
|
||||
{
|
||||
ret[0] = i;
|
||||
ret[1] = j;
|
||||
}
|
||||
|
@ -7,14 +7,17 @@
|
||||
* };
|
||||
*/
|
||||
|
||||
bool checkSymmetric(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);
|
||||
return checkSymmetric(left->left, right->right) &&
|
||||
checkSymmetric(left->right, right->left);
|
||||
}
|
||||
|
||||
bool isSymmetric(struct TreeNode* root){
|
||||
bool isSymmetric(struct TreeNode *root)
|
||||
{
|
||||
return root == NULL || checkSymmetric(root->left, root->right);
|
||||
}
|
||||
|
@ -7,16 +7,17 @@
|
||||
* };
|
||||
*/
|
||||
|
||||
int maxval(int a, int b) {
|
||||
int maxval(int a, int b)
|
||||
{
|
||||
if (a > b)
|
||||
return a;
|
||||
else
|
||||
return b;
|
||||
}
|
||||
int maxDepth(struct TreeNode* root){
|
||||
int maxDepth(struct TreeNode *root)
|
||||
{
|
||||
if (root == NULL)
|
||||
return 0;
|
||||
else
|
||||
return 1 + maxval(maxDepth(root->left), maxDepth(root->right));
|
||||
}
|
||||
|
||||
|
@ -7,10 +7,12 @@
|
||||
* };
|
||||
*/
|
||||
|
||||
struct TreeNode* convertBST(int *nums, int left, int right) {
|
||||
struct TreeNode *convertBST(int *nums, int left, int right)
|
||||
{
|
||||
if (left > right)
|
||||
return NULL;
|
||||
else {
|
||||
else
|
||||
{
|
||||
int mid = (right + left) / 2;
|
||||
struct TreeNode *new_val = malloc(sizeof(struct TreeNode));
|
||||
new_val->val = nums[mid];
|
||||
@ -20,10 +22,10 @@ struct TreeNode* convertBST(int *nums, int left, int right) {
|
||||
}
|
||||
}
|
||||
|
||||
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
|
||||
struct TreeNode *sortedArrayToBST(int *nums, int numsSize)
|
||||
{
|
||||
if (numsSize == 0)
|
||||
return NULL;
|
||||
else
|
||||
return convertBST(nums, 0, numsSize - 1);
|
||||
}
|
||||
|
||||
|
@ -1,14 +1,18 @@
|
||||
void duplicateZeros(int* arr, int arrSize){
|
||||
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++) {
|
||||
for (i = 0; i < arrSize; i++)
|
||||
{
|
||||
tmp[i] = arr[i];
|
||||
}
|
||||
i = 0;
|
||||
for(start = 0; start < arrSize; start++) {
|
||||
for (start = 0; start < arrSize; start++)
|
||||
{
|
||||
arr[start] = tmp[i];
|
||||
if(tmp[i] == 0) {
|
||||
if (tmp[i] == 0)
|
||||
{
|
||||
start++;
|
||||
if (start < arrSize)
|
||||
arr[start] = 0;
|
||||
@ -16,5 +20,3 @@ void duplicateZeros(int* arr, int arrSize){
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,8 +1,10 @@
|
||||
struct TreeNode* buildBST(struct ListNode* head, struct ListNode* tail) {
|
||||
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) {
|
||||
while (fast != tail && fast->next != tail)
|
||||
{
|
||||
fast = fast->next->next;
|
||||
slow = slow->next;
|
||||
}
|
||||
@ -12,10 +14,10 @@ struct TreeNode* buildBST(struct ListNode* head, struct ListNode* tail) {
|
||||
node->right = buildBST(slow->next, tail);
|
||||
return node;
|
||||
}
|
||||
struct TreeNode* sortedListToBST(struct ListNode* head){
|
||||
struct TreeNode *sortedListToBST(struct ListNode *head)
|
||||
{
|
||||
if (!head)
|
||||
return NULL;
|
||||
else
|
||||
return buildBST(head, NULL);
|
||||
}
|
||||
|
||||
|
@ -1,17 +1,17 @@
|
||||
// Fucntion to calculate min of values a and b
|
||||
int min(int a, int b){
|
||||
return ((a<b)?a: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){
|
||||
int maxArea(int *height, int heightSize)
|
||||
{
|
||||
|
||||
// Start with maximum container width
|
||||
int start = 0;
|
||||
int end = heightSize - 1;
|
||||
int res = 0;
|
||||
|
||||
while(start<end){
|
||||
while (start < end)
|
||||
{
|
||||
// Calculate current area by taking minimum of two heights
|
||||
int currArea = (end - start) * min(height[start], height[end]);
|
||||
|
||||
@ -22,9 +22,7 @@ int maxArea(int* height, int heightSize){
|
||||
start = start + 1;
|
||||
else
|
||||
end = end - 1;
|
||||
|
||||
}
|
||||
|
||||
return res;
|
||||
|
||||
}
|
||||
|
@ -1,19 +1,19 @@
|
||||
int max(int a, int b) {
|
||||
return a >= b ? a : b;
|
||||
}
|
||||
int max(int a, int b) { return a >= b ? a : b; }
|
||||
|
||||
int height(struct TreeNode* root) {
|
||||
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){
|
||||
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);
|
||||
return abs(left - right) <= 1 && isBalanced(root->left) &&
|
||||
isBalanced(root->right);
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,9 @@
|
||||
bool hasPathSum(struct TreeNode* root, int sum) {
|
||||
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);
|
||||
return hasPathSum(root->left, sum - root->val) ||
|
||||
hasPathSum(root->right, sum - root->val);
|
||||
}
|
||||
|
@ -1,12 +1,16 @@
|
||||
int distanceBetweenBusStops(int* distance, int distanceSize, int start, int destination){
|
||||
int distanceBetweenBusStops(int *distance, int distanceSize, int start,
|
||||
int destination)
|
||||
{
|
||||
|
||||
int sum1 = 0, sum2 = 0;
|
||||
if (start > destination) {
|
||||
if (start > destination)
|
||||
{
|
||||
int tmp = start;
|
||||
start = destination;
|
||||
destination = tmp;
|
||||
}
|
||||
for (auto i = 0; i < distanceSize; ++i) {
|
||||
for (auto i = 0; i < distanceSize; ++i)
|
||||
{
|
||||
if (i >= start && i < destination)
|
||||
sum1 += distance[i];
|
||||
else
|
||||
|
@ -1,4 +1,5 @@
|
||||
int maxNumberOfBalloons(char * text){
|
||||
int maxNumberOfBalloons(char *text)
|
||||
{
|
||||
/*
|
||||
0 -> b,
|
||||
1 -> a,
|
||||
@ -9,16 +10,26 @@ int maxNumberOfBalloons(char * text){
|
||||
int count_letters[5] = {0};
|
||||
int i, min_counter_ballons;
|
||||
|
||||
for (char *ptr = text; *ptr; ptr++) {
|
||||
if (*ptr == 'b') {
|
||||
for (char *ptr = text; *ptr; ptr++)
|
||||
{
|
||||
if (*ptr == 'b')
|
||||
{
|
||||
count_letters[0]++;
|
||||
} else if(*ptr == 'a') {
|
||||
}
|
||||
else if (*ptr == 'a')
|
||||
{
|
||||
count_letters[1]++;
|
||||
} else if (*ptr == 'l') {
|
||||
}
|
||||
else if (*ptr == 'l')
|
||||
{
|
||||
count_letters[2]++;
|
||||
} else if(*ptr == 'o') {
|
||||
}
|
||||
else if (*ptr == 'o')
|
||||
{
|
||||
count_letters[3]++;
|
||||
} else if(*ptr == 'n') {
|
||||
}
|
||||
else if (*ptr == 'n')
|
||||
{
|
||||
count_letters[4]++;
|
||||
}
|
||||
}
|
||||
@ -27,9 +38,11 @@ int maxNumberOfBalloons(char * text){
|
||||
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 */
|
||||
/* 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++) {
|
||||
for (i = 1; i < 5; i++)
|
||||
{
|
||||
if (count_letters[i] < min_counter_ballons)
|
||||
min_counter_ballons = count_letters[i];
|
||||
}
|
||||
|
@ -1,5 +1,7 @@
|
||||
char *getOne(char c){
|
||||
switch (c) {
|
||||
char *getOne(char c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '9':
|
||||
return "IX";
|
||||
|
||||
@ -35,8 +37,10 @@ char *getOne(char c){
|
||||
}
|
||||
}
|
||||
|
||||
char *getTen(char c){
|
||||
switch (c) {
|
||||
char *getTen(char c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '9':
|
||||
return "XC";
|
||||
|
||||
@ -70,11 +74,12 @@ char *getTen(char c){
|
||||
default:
|
||||
return NULL;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
char *getHundred(char c){
|
||||
switch (c) {
|
||||
char *getHundred(char c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '9':
|
||||
return "CM";
|
||||
|
||||
@ -110,8 +115,10 @@ char *getHundred(char c){
|
||||
}
|
||||
}
|
||||
|
||||
char *getThousand(char c){
|
||||
switch (c) {
|
||||
char *getThousand(char c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '3':
|
||||
return "MMM";
|
||||
|
||||
@ -126,10 +133,8 @@ char *getThousand(char c){
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
char * intToRoman(int num){
|
||||
char *intToRoman(int num)
|
||||
{
|
||||
int length;
|
||||
char number[5];
|
||||
char *s = malloc(16 * sizeof(char));
|
||||
@ -138,13 +143,16 @@ char * intToRoman(int num){
|
||||
|
||||
length = strlen(number);
|
||||
|
||||
switch (length){
|
||||
switch (length)
|
||||
{
|
||||
case 4:
|
||||
sprintf(s,"%s%s%s%s", getThousand(number[0]), getHundred(number[1]), getTen(number[2]), getOne(number[3]));
|
||||
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]));
|
||||
sprintf(s, "%s%s%s", getHundred(number[0]), getTen(number[1]),
|
||||
getOne(number[2]));
|
||||
|
||||
break;
|
||||
|
||||
|
@ -1,12 +1,12 @@
|
||||
#define MAP_SIZE 2048
|
||||
|
||||
int cmpvalue(const void *a, const void *b) {
|
||||
return *(int *)b - *(int *)a;
|
||||
}
|
||||
bool uniqueOccurrences(int* arr, int arrSize){
|
||||
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++) {
|
||||
for (i = 0; i < arrSize; i++)
|
||||
{
|
||||
if (arr[i] < 0)
|
||||
map[arr[i] + MAP_SIZE / 2] += 1;
|
||||
else
|
||||
@ -16,7 +16,8 @@ bool uniqueOccurrences(int* arr, int arrSize){
|
||||
Ex: 3 2 1 0 0 0 0 */
|
||||
qsort(map, MAP_SIZE, sizeof(int), cmpvalue);
|
||||
i = 0;
|
||||
while(map[i]) {
|
||||
while (map[i])
|
||||
{
|
||||
if (map[i] == map[i + 1])
|
||||
return 0;
|
||||
i++;
|
||||
|
@ -1,15 +1,15 @@
|
||||
int maxcmp(int a, int b) {
|
||||
return (a >= b)? a : b;
|
||||
}
|
||||
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){
|
||||
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++) {
|
||||
for (int i = 1; i < pricesSize; i++)
|
||||
{
|
||||
maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]);
|
||||
maxSoFar = maxcmp(maxSoFar, maxCur);
|
||||
}
|
||||
|
@ -1,12 +1,18 @@
|
||||
bool isPalindrome(char * s){
|
||||
bool isPalindrome(char *s)
|
||||
{
|
||||
int start = 0, end = strlen(s) - 1;
|
||||
while(start < end) {
|
||||
if (!isalpha(s[start]) && !isalnum(s[start])) {
|
||||
while (start < end)
|
||||
{
|
||||
if (!isalpha(s[start]) && !isalnum(s[start]))
|
||||
{
|
||||
start++;
|
||||
}
|
||||
else if (!isalpha(s[end]) && !isalnum(s[end])) {
|
||||
else if (!isalpha(s[end]) && !isalnum(s[end]))
|
||||
{
|
||||
end--;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
char c1 = tolower(s[start]);
|
||||
char c2 = tolower(s[end]);
|
||||
if (c1 != c2)
|
||||
|
@ -1,10 +1,15 @@
|
||||
int romanToInt(char * s){
|
||||
int romanToInt(char *s)
|
||||
{
|
||||
int romanToInt = 0;
|
||||
for (int i = 0; i < strlen(s); i++) {
|
||||
switch(s[i]) {
|
||||
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') {
|
||||
if (i + 1 < strlen(s))
|
||||
{
|
||||
if (s[i + 1] == 'V' || s[i + 1] == 'X')
|
||||
{
|
||||
romanToInt -= 1;
|
||||
break;
|
||||
}
|
||||
@ -15,8 +20,10 @@ int romanToInt(char * s){
|
||||
romanToInt += 5;
|
||||
break;
|
||||
case 'X':
|
||||
if (i+1 < strlen(s)) {
|
||||
if (s[i + 1] == 'L' || s[i + 1] == 'C') {
|
||||
if (i + 1 < strlen(s))
|
||||
{
|
||||
if (s[i + 1] == 'L' || s[i + 1] == 'C')
|
||||
{
|
||||
romanToInt -= 10;
|
||||
break;
|
||||
}
|
||||
@ -27,8 +34,10 @@ int romanToInt(char * s){
|
||||
romanToInt += 50;
|
||||
break;
|
||||
case 'C':
|
||||
if (i+1 < strlen(s)) {
|
||||
if (s[i + 1] == 'D' || s[i + 1] == 'M') {
|
||||
if (i + 1 < strlen(s))
|
||||
{
|
||||
if (s[i + 1] == 'D' || s[i + 1] == 'M')
|
||||
{
|
||||
romanToInt -= 100;
|
||||
break;
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
int singleNumber(int* nums, int numsSize){
|
||||
int singleNumber(int *nums, int numsSize)
|
||||
{
|
||||
int i, result = 0;
|
||||
for (i = 0; i < numsSize; i++)
|
||||
result = result ^ nums[i];
|
||||
|
@ -5,12 +5,15 @@
|
||||
* struct ListNode *next;
|
||||
* };
|
||||
*/
|
||||
bool hasCycle(struct ListNode *head) {
|
||||
bool hasCycle(struct ListNode *head)
|
||||
{
|
||||
struct ListNode *fast = head, *slow = head;
|
||||
while( slow && fast && fast->next ){
|
||||
while (slow && fast && fast->next)
|
||||
{
|
||||
fast = fast->next->next;
|
||||
slow = slow->next;
|
||||
if(fast==slow) return true;
|
||||
if (fast == slow)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
@ -1,14 +1,18 @@
|
||||
struct ListNode *detectCycle(struct ListNode *head) {
|
||||
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) {
|
||||
while (fast && fast->next)
|
||||
{
|
||||
slow = slow->next;
|
||||
fast = fast->next->next;
|
||||
if(slow == fast) {
|
||||
if (slow == fast)
|
||||
{
|
||||
struct ListNode *entry = head;
|
||||
while(slow != entry) {
|
||||
while (slow != entry)
|
||||
{
|
||||
slow = slow->next;
|
||||
entry = entry->next;
|
||||
}
|
||||
|
@ -1,6 +1,8 @@
|
||||
int findMin(int* nums, int numsSize){
|
||||
int findMin(int *nums, int numsSize)
|
||||
{
|
||||
int low = 0, high = numsSize - 1;
|
||||
while (low < high) {
|
||||
while (low < high)
|
||||
{
|
||||
int mid = low + (high - low) / 2;
|
||||
/* minimum is on left side */
|
||||
if (nums[mid] < nums[high])
|
||||
|
@ -1,8 +1,11 @@
|
||||
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
|
||||
struct ListNode *getIntersectionNode(struct ListNode *headA,
|
||||
struct ListNode *headB)
|
||||
{
|
||||
struct ListNode *cur1 = headA, *cur2 = headB;
|
||||
if (cur1 == NULL || cur2 == NULL)
|
||||
return NULL;
|
||||
while (cur1 && cur2 && cur1 != cur2) {
|
||||
while (cur1 && cur2 && cur1 != cur2)
|
||||
{
|
||||
cur1 = cur1->next;
|
||||
cur2 = cur2->next;
|
||||
if (cur1 == cur2)
|
||||
@ -13,5 +16,4 @@ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *he
|
||||
cur2 = headA;
|
||||
}
|
||||
return cur1;
|
||||
|
||||
}
|
||||
|
@ -1,13 +1,17 @@
|
||||
/* Boyer-Moore Majority Vote Algorithm
|
||||
* http://www.cs.utexas.edu/~moore/best-ideas/mjrty/ */
|
||||
int majorityElement(int* nums, int numsSize){
|
||||
int majorityElement(int *nums, int numsSize)
|
||||
{
|
||||
int count = 1;
|
||||
int majorNum = nums[0];
|
||||
for (int i = 1; i < numsSize; i++) {
|
||||
if(count == 0) {
|
||||
for (int i = 1; i < numsSize; i++)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
majorNum = nums[i];
|
||||
count++;
|
||||
} else if (majorNum == nums[i])
|
||||
}
|
||||
else if (majorNum == nums[i])
|
||||
count++;
|
||||
else
|
||||
count--;
|
||||
|
@ -9,13 +9,15 @@
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
typedef struct {
|
||||
typedef struct
|
||||
{
|
||||
int *values;
|
||||
int CurrentIndex;
|
||||
int NumberOfNodes;
|
||||
} BSTIterator;
|
||||
|
||||
void TraverseAndAssign(struct TreeNode *root, BSTIterator *obj) {
|
||||
void TraverseAndAssign(struct TreeNode *root, BSTIterator *obj)
|
||||
{
|
||||
if (!root)
|
||||
return;
|
||||
if (root->left)
|
||||
@ -26,7 +28,8 @@ void TraverseAndAssign(struct TreeNode *root, BSTIterator *obj) {
|
||||
TraverseAndAssign(root->right, obj);
|
||||
}
|
||||
|
||||
int TotalNodes(struct TreeNode *root) {
|
||||
int TotalNodes(struct TreeNode *root)
|
||||
{
|
||||
if (!root)
|
||||
return 0;
|
||||
int nodes_left = TotalNodes(root->left);
|
||||
@ -34,7 +37,8 @@ int TotalNodes(struct TreeNode *root) {
|
||||
return nodes_left + nodes_right + 1;
|
||||
}
|
||||
|
||||
BSTIterator* bSTIteratorCreate(struct TreeNode* root) {
|
||||
BSTIterator *bSTIteratorCreate(struct TreeNode *root)
|
||||
{
|
||||
int n = TotalNodes(root);
|
||||
int size = n + 1;
|
||||
printf("%d", size);
|
||||
@ -49,22 +53,26 @@ BSTIterator* bSTIteratorCreate(struct TreeNode* root) {
|
||||
}
|
||||
|
||||
/** @return the next smallest number */
|
||||
int bSTIteratorNext(BSTIterator* obj) {
|
||||
int bSTIteratorNext(BSTIterator *obj)
|
||||
{
|
||||
int NextValue = obj->values[obj->CurrentIndex];
|
||||
obj->CurrentIndex++;
|
||||
return NextValue;
|
||||
}
|
||||
|
||||
/** @return whether we have a next smallest number */
|
||||
bool bSTIteratorHasNext(BSTIterator* obj) {
|
||||
if(!obj->NumberOfNodes) {
|
||||
bool bSTIteratorHasNext(BSTIterator *obj)
|
||||
{
|
||||
if (!obj->NumberOfNodes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
printf(" Here ");
|
||||
return (obj->values[obj->CurrentIndex] == INT_MAX) ? false : true;
|
||||
}
|
||||
|
||||
void bSTIteratorFree(BSTIterator* obj) {
|
||||
void bSTIteratorFree(BSTIterator *obj)
|
||||
{
|
||||
free(obj->values);
|
||||
free(obj);
|
||||
}
|
||||
|
@ -1,9 +1,12 @@
|
||||
void rotate(int* nums, int numsSize, int k){
|
||||
for(int i = 1; i <= k; i++){
|
||||
void rotate(int *nums, int numsSize, int k)
|
||||
{
|
||||
for (int i = 1; i <= k; i++)
|
||||
{
|
||||
int j;
|
||||
int lastElement;
|
||||
lastElement = nums[numsSize - 1];
|
||||
for(j = numsSize - 1; j > 0; j--){
|
||||
for (j = numsSize - 1; j > 0; j--)
|
||||
{
|
||||
nums[j] = nums[j - 1];
|
||||
}
|
||||
nums[0] = lastElement;
|
||||
|
@ -1,13 +1,25 @@
|
||||
uint32_t reverseBits(uint32_t n) {
|
||||
uint32_t reverseBits(uint32_t n)
|
||||
{
|
||||
uint TotalBits = 32;
|
||||
uint32_t reverse_int = 0; // stored in memory as 32 bits, each bit valued 0
|
||||
uint i;
|
||||
for(i = 0; i < TotalBits; i++) {
|
||||
if((n & (UINT32_C(1) << i))) //if the bit on the ith position of 32 bit input is 1, then proceed
|
||||
//Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, since just 1 is treated as int which cannot be shifted left more than 30 times
|
||||
reverse_int = reverse_int | (UINT32_C(1) << (TotalBits - 1 - i)); //Convert the ith bit from the end in reverse_int from 0 to 1, if ith bit from beginning in n is 1
|
||||
//This is achieved by using bitwise OR on reverse_int (where ith bit from end is currently 0) and
|
||||
//1 shifted left 31 - i bits (to ith bit from the end)
|
||||
for (i = 0; i < TotalBits; i++)
|
||||
{
|
||||
if ((n &
|
||||
(UINT32_C(1)
|
||||
<< i))) // if the bit on the ith position of 32 bit input is 1,
|
||||
// then proceed Further note the use of UINT32_C to convert
|
||||
// 1 to unsigned 32 bit int, since just 1 is treated as int
|
||||
// which cannot be shifted left more than 30 times
|
||||
reverse_int =
|
||||
reverse_int |
|
||||
(UINT32_C(1)
|
||||
<< (TotalBits - 1 -
|
||||
i)); // Convert the ith bit from the end in reverse_int
|
||||
// from 0 to 1, if ith bit from beginning in n is 1
|
||||
// This is achieved by using bitwise OR on reverse_int
|
||||
// (where ith bit from end is currently 0) and 1
|
||||
// shifted left 31 - i bits (to ith bit from the end)
|
||||
}
|
||||
return reverse_int;
|
||||
}
|
@ -1,9 +1,14 @@
|
||||
int hammingWeight(uint32_t n) {
|
||||
int hammingWeight(uint32_t n)
|
||||
{
|
||||
int TotalBits = 32;
|
||||
int i, weight = 0;
|
||||
for(i = 0; i < TotalBits; i++) {
|
||||
if(n & (UINT32_C(1) << i)) //if the bit on the ith position of 32 bit input is 1, then proceed
|
||||
//Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, as just 1 is treated as int which cannot be shifted left more than 30 times
|
||||
for (i = 0; i < TotalBits; i++)
|
||||
{
|
||||
if (n & (UINT32_C(1)
|
||||
<< i)) // if the bit on the ith position of 32 bit input is 1,
|
||||
// then proceed Further note the use of UINT32_C to
|
||||
// convert 1 to unsigned 32 bit int, as just 1 is treated
|
||||
// as int which cannot be shifted left more than 30 times
|
||||
weight += 1;
|
||||
}
|
||||
return weight;
|
||||
|
@ -6,7 +6,8 @@
|
||||
* };
|
||||
*/
|
||||
|
||||
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
|
||||
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2)
|
||||
{
|
||||
struct ListNode *head = NULL;
|
||||
struct ListNode *walk = NULL;
|
||||
struct ListNode *tmp = NULL;
|
||||
@ -16,17 +17,20 @@ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
|
||||
int val2 = 0;
|
||||
int val = 0;
|
||||
|
||||
while(l1 != NULL || l2 != NULL || carry) {
|
||||
while (l1 != NULL || l2 != NULL || carry)
|
||||
{
|
||||
val1 = 0;
|
||||
val2 = 0;
|
||||
val = 0;
|
||||
|
||||
if(l1) {
|
||||
if (l1)
|
||||
{
|
||||
val1 = l1->val;
|
||||
l1 = l1->next;
|
||||
}
|
||||
|
||||
if(l2) {
|
||||
if (l2)
|
||||
{
|
||||
val2 = l2->val;
|
||||
l2 = l2->next;
|
||||
}
|
||||
@ -38,9 +42,12 @@ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
|
||||
tmp->val = val % 10;
|
||||
tmp->next = NULL;
|
||||
|
||||
if(!head) {
|
||||
if (!head)
|
||||
{
|
||||
head = walk = tmp;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
walk->next = tmp;
|
||||
walk = walk->next;
|
||||
}
|
||||
@ -48,4 +55,3 @@ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
|
||||
|
||||
return head;
|
||||
}
|
||||
|
||||
|
@ -1,9 +1,12 @@
|
||||
bool isValid(char * s){
|
||||
bool isValid(char *s)
|
||||
{
|
||||
int i, k = 0, len = strlen(s);
|
||||
char *store = calloc(len, sizeof(char));
|
||||
|
||||
for( i = 0; s[i] != '\0'; i++) {
|
||||
switch(s[i]) {
|
||||
for (i = 0; s[i] != '\0'; i++)
|
||||
{
|
||||
switch (s[i])
|
||||
{
|
||||
case '(':
|
||||
case '{':
|
||||
case '[':
|
||||
|
@ -1,5 +1,7 @@
|
||||
int rangeBitwiseAnd(int m, int n){
|
||||
while (m < n) {
|
||||
int rangeBitwiseAnd(int m, int n)
|
||||
{
|
||||
while (m < n)
|
||||
{
|
||||
n &= n - 1;
|
||||
}
|
||||
return n;
|
||||
|
@ -1,9 +1,13 @@
|
||||
struct ListNode* removeElements(struct ListNode* head, int val){
|
||||
struct ListNode *removeElements(struct ListNode *head, int val)
|
||||
{
|
||||
if (head == NULL)
|
||||
return NULL;
|
||||
if(head->val == val) {
|
||||
if (head->val == val)
|
||||
{
|
||||
return removeElements(head->next, val);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
head->next = removeElements(head->next, val);
|
||||
}
|
||||
return head;
|
||||
|
@ -6,10 +6,11 @@
|
||||
* };
|
||||
*/
|
||||
|
||||
|
||||
struct ListNode* reverseList(struct ListNode* head){
|
||||
struct ListNode *reverseList(struct ListNode *head)
|
||||
{
|
||||
struct ListNode *res = NULL;
|
||||
while(head) {
|
||||
while (head)
|
||||
{
|
||||
struct ListNode *pre_node = head;
|
||||
head = head->next;
|
||||
pre_node->next = res;
|
||||
|
@ -1,7 +1,8 @@
|
||||
/*
|
||||
* Iterative approach
|
||||
*/
|
||||
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
|
||||
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
|
||||
{
|
||||
struct ListNode *list = NULL;
|
||||
struct ListNode *tmp = NULL;
|
||||
|
||||
@ -10,20 +11,28 @@ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
|
||||
if (!l2)
|
||||
return l1;
|
||||
|
||||
if (l1 && l2) {
|
||||
if (l1->val < l2->val) {
|
||||
if (l1 && l2)
|
||||
{
|
||||
if (l1->val < l2->val)
|
||||
{
|
||||
list = tmp = l1;
|
||||
l1 = l1->next;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
list = tmp = l2;
|
||||
l2 = l2->next;
|
||||
}
|
||||
|
||||
while(l1 && l2) {
|
||||
if (l1->val < l2->val) {
|
||||
while (l1 && l2)
|
||||
{
|
||||
if (l1->val < l2->val)
|
||||
{
|
||||
tmp->next = l1;
|
||||
l1 = l1->next;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
tmp->next = l2;
|
||||
l2 = l2->next;
|
||||
}
|
||||
@ -44,17 +53,20 @@ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
|
||||
/*
|
||||
* Recursive approach
|
||||
*/
|
||||
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
|
||||
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
|
||||
{
|
||||
if (!l1)
|
||||
return l2;
|
||||
if (!l2)
|
||||
return l1;
|
||||
if(l1->val < l2->val) {
|
||||
if (l1->val < l2->val)
|
||||
{
|
||||
l1->next = mergeTwoLists(l1->next, l2);
|
||||
return l1;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
l2->next = mergeTwoLists(l1, l2->next);
|
||||
return l2;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,8 +1,7 @@
|
||||
int *cmpval (const void *a, const void *b) {
|
||||
return *(int *)b - *(int *)a;
|
||||
}
|
||||
int *cmpval(const void *a, const void *b) { return *(int *)b - *(int *)a; }
|
||||
|
||||
int findKthLargest(int* nums, int numsSize, int k){
|
||||
int findKthLargest(int *nums, int numsSize, int k)
|
||||
{
|
||||
qsort(nums, numsSize, sizeof(int), cmpval);
|
||||
return nums[k - 1];
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user