mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-22 05:21:49 +03:00
Merge branch 'auto_clang-format' of https://github.com/kvedala/C into auto_clang-format
This commit is contained in:
commit
2829b58c98
@ -1,49 +1,49 @@
|
|||||||
// Client side implementation of UDP client-server model
|
// Client side implementation of UDP client-server model
|
||||||
#include <stdio.h>
|
#include <arpa/inet.h>
|
||||||
#include <stdlib.h>
|
#include <netinet/in.h>
|
||||||
#include <unistd.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <stdlib.h>
|
||||||
#include <sys/types.h>
|
#include <string.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <arpa/inet.h>
|
#include <sys/types.h>
|
||||||
#include <netinet/in.h>
|
#include <unistd.h>
|
||||||
|
|
||||||
#define PORT 8080
|
#define PORT 8080
|
||||||
#define MAXLINE 1024
|
#define MAXLINE 1024
|
||||||
|
|
||||||
// Driver code
|
// Driver code
|
||||||
int main() {
|
int main()
|
||||||
int sockfd;
|
{
|
||||||
char buffer[MAXLINE];
|
int sockfd;
|
||||||
char *hello = "Hello from client";
|
char buffer[MAXLINE];
|
||||||
struct sockaddr_in servaddr;
|
char *hello = "Hello from client";
|
||||||
|
struct sockaddr_in servaddr;
|
||||||
|
|
||||||
// Creating socket file descriptor
|
// 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);
|
perror("socket creation failed");
|
||||||
}
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
|
|
||||||
memset(&servaddr, 0, sizeof(servaddr));
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
|
|
||||||
// Filling server information
|
|
||||||
servaddr.sin_family = AF_INET;
|
|
||||||
servaddr.sin_port = htons(PORT);
|
|
||||||
servaddr.sin_addr.s_addr = INADDR_ANY;
|
|
||||||
|
|
||||||
int n, len;
|
|
||||||
|
|
||||||
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);
|
|
||||||
buffer[n] = '\0';
|
|
||||||
printf("Server : %s\n", buffer);
|
|
||||||
|
|
||||||
close(sockfd);
|
// Filling server information
|
||||||
return 0;
|
servaddr.sin_family = AF_INET;
|
||||||
}
|
servaddr.sin_port = htons(PORT);
|
||||||
|
servaddr.sin_addr.s_addr = INADDR_ANY;
|
||||||
|
|
||||||
|
int n, len;
|
||||||
|
|
||||||
|
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);
|
||||||
|
buffer[n] = '\0';
|
||||||
|
printf("Server : %s\n", buffer);
|
||||||
|
|
||||||
|
close(sockfd);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
@ -1,55 +1,54 @@
|
|||||||
// Server side implementation of UDP client-server model
|
// Server side implementation of UDP client-server model
|
||||||
#include <stdio.h>
|
#include <arpa/inet.h>
|
||||||
#include <stdlib.h>
|
#include <netinet/in.h>
|
||||||
#include <unistd.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <stdlib.h>
|
||||||
#include <sys/types.h>
|
#include <string.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <arpa/inet.h>
|
#include <sys/types.h>
|
||||||
#include <netinet/in.h>
|
#include <unistd.h>
|
||||||
|
|
||||||
#define PORT 8080
|
#define PORT 8080
|
||||||
#define MAXLINE 1024
|
#define MAXLINE 1024
|
||||||
|
|
||||||
// Driver code
|
// Driver code
|
||||||
int main() {
|
int main()
|
||||||
int sockfd;
|
{
|
||||||
char buffer[MAXLINE];
|
int sockfd;
|
||||||
char *hello = "Hello from server";
|
char buffer[MAXLINE];
|
||||||
struct sockaddr_in servaddr, cliaddr;
|
char *hello = "Hello from server";
|
||||||
|
struct sockaddr_in servaddr, cliaddr;
|
||||||
// Creating socket file descriptor
|
|
||||||
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
|
// Creating socket file descriptor
|
||||||
perror("socket creation failed");
|
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
|
||||||
exit(EXIT_FAILURE);
|
{
|
||||||
}
|
perror("socket creation failed");
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
memset(&servaddr, 0, sizeof(servaddr));
|
}
|
||||||
memset(&cliaddr, 0, sizeof(cliaddr));
|
|
||||||
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
// Filling server information
|
memset(&cliaddr, 0, sizeof(cliaddr));
|
||||||
servaddr.sin_family = AF_INET; // IPv4
|
|
||||||
servaddr.sin_addr.s_addr = INADDR_ANY;
|
// Filling server information
|
||||||
servaddr.sin_port = htons(PORT);
|
servaddr.sin_family = AF_INET; // IPv4
|
||||||
|
servaddr.sin_addr.s_addr = INADDR_ANY;
|
||||||
// Bind the socket with the server address
|
servaddr.sin_port = htons(PORT);
|
||||||
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
|
|
||||||
sizeof(servaddr)) < 0 )
|
// Bind the socket with the server address
|
||||||
{
|
if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
|
||||||
perror("bind failed");
|
{
|
||||||
exit(EXIT_FAILURE);
|
perror("bind failed");
|
||||||
}
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
int len, n;
|
|
||||||
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
|
int len, n;
|
||||||
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
|
n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL,
|
||||||
&len);
|
(struct sockaddr *)&cliaddr, &len);
|
||||||
buffer[n] = '\0';
|
buffer[n] = '\0';
|
||||||
printf("Client : %s\n", buffer);
|
printf("Client : %s\n", buffer);
|
||||||
sendto(sockfd, (const char *)hello, strlen(hello),
|
sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM,
|
||||||
MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
|
(const struct sockaddr *)&cliaddr, len);
|
||||||
len);
|
printf("Hello message sent.\n");
|
||||||
printf("Hello message sent.\n");
|
|
||||||
|
return 0;
|
||||||
return 0;
|
}
|
||||||
}
|
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
// Write CPP code here
|
// Write CPP code here
|
||||||
#include <netdb.h>
|
#include <arpa/inet.h>
|
||||||
#include <stdio.h>
|
#include <netdb.h>
|
||||||
#include <stdlib.h>
|
#include <stdio.h>
|
||||||
#include <unistd.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <arpa/inet.h>
|
#include <unistd.h>
|
||||||
#define MAX 80
|
#define MAX 80
|
||||||
#define PORT 8080
|
#define PORT 8080
|
||||||
#define SA struct sockaddr
|
#define SA struct sockaddr
|
||||||
|
@ -1,95 +1,101 @@
|
|||||||
#include <netdb.h>
|
#include <netdb.h>
|
||||||
#include <netinet/in.h>
|
#include <netinet/in.h>
|
||||||
#include <stdlib.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <sys/socket.h>
|
#include <stdlib.h>
|
||||||
#include <sys/types.h>
|
#include <string.h>
|
||||||
#define MAX 80
|
#include <sys/socket.h>
|
||||||
#define PORT 8080
|
#include <sys/types.h>
|
||||||
#define SA struct sockaddr
|
#include <unistd.h>
|
||||||
|
#define MAX 80
|
||||||
// Function designed for chat between client and server.
|
#define PORT 8080
|
||||||
void func(int sockfd)
|
#define SA struct sockaddr
|
||||||
{
|
|
||||||
char buff[MAX];
|
// Function designed for chat between client and server.
|
||||||
int n;
|
void func(int sockfd)
|
||||||
// infinite loop for chat
|
{
|
||||||
for (;;) {
|
char buff[MAX];
|
||||||
bzero(buff, MAX);
|
int n;
|
||||||
|
// infinite loop for chat
|
||||||
// read the message from client and copy it in buffer
|
for (;;)
|
||||||
read(sockfd, buff, sizeof(buff));
|
{
|
||||||
// print buffer which contains the client contents
|
bzero(buff, MAX);
|
||||||
printf("From client: %s\t To client : ", buff);
|
|
||||||
bzero(buff, MAX);
|
// read the message from client and copy it in buffer
|
||||||
n = 0;
|
read(sockfd, buff, sizeof(buff));
|
||||||
// copy server message in the buffer
|
// print buffer which contains the client contents
|
||||||
while ((buff[n++] = getchar()) != '\n')
|
printf("From client: %s\t To client : ", buff);
|
||||||
;
|
bzero(buff, MAX);
|
||||||
|
n = 0;
|
||||||
// and send that buffer to client
|
// copy server message in the buffer
|
||||||
write(sockfd, buff, sizeof(buff));
|
while ((buff[n++] = getchar()) != '\n')
|
||||||
|
;
|
||||||
// if msg contains "Exit" then server exit and chat ended.
|
|
||||||
if (strncmp("exit", buff, 4) == 0) {
|
// and send that buffer to client
|
||||||
printf("Server Exit...\n");
|
write(sockfd, buff, sizeof(buff));
|
||||||
break;
|
|
||||||
}
|
// if msg contains "Exit" then server exit and chat ended.
|
||||||
}
|
if (strncmp("exit", buff, 4) == 0)
|
||||||
}
|
{
|
||||||
|
printf("Server Exit...\n");
|
||||||
// Driver function
|
break;
|
||||||
int main()
|
}
|
||||||
{
|
}
|
||||||
int sockfd, connfd, len;
|
}
|
||||||
struct sockaddr_in servaddr, cli;
|
|
||||||
|
// Driver function
|
||||||
// socket create and verification
|
int main()
|
||||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
{
|
||||||
if (sockfd == -1) {
|
int sockfd, connfd, len;
|
||||||
printf("socket creation failed...\n");
|
struct sockaddr_in servaddr, cli;
|
||||||
exit(0);
|
|
||||||
}
|
// socket create and verification
|
||||||
|
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
if (sockfd == -1)
|
||||||
|
{
|
||||||
|
printf("socket creation failed...\n");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
printf("Socket successfully created..\n");
|
printf("Socket successfully created..\n");
|
||||||
bzero(&servaddr, sizeof(servaddr));
|
bzero(&servaddr, sizeof(servaddr));
|
||||||
|
|
||||||
// assign IP, PORT
|
// assign IP, PORT
|
||||||
servaddr.sin_family = AF_INET;
|
servaddr.sin_family = AF_INET;
|
||||||
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||||
servaddr.sin_port = htons(PORT);
|
servaddr.sin_port = htons(PORT);
|
||||||
|
|
||||||
// Binding newly created socket to given IP and verification
|
// 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);
|
printf("socket bind failed...\n");
|
||||||
}
|
exit(0);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
printf("Socket successfully binded..\n");
|
printf("Socket successfully binded..\n");
|
||||||
|
|
||||||
// Now server is ready to listen and verification
|
// Now server is ready to listen and verification
|
||||||
if ((listen(sockfd, 5)) != 0) {
|
if ((listen(sockfd, 5)) != 0)
|
||||||
printf("Listen failed...\n");
|
{
|
||||||
exit(0);
|
printf("Listen failed...\n");
|
||||||
}
|
exit(0);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
printf("Server listening..\n");
|
printf("Server listening..\n");
|
||||||
len = sizeof(cli);
|
len = sizeof(cli);
|
||||||
|
|
||||||
// Accept the data packet from client and verification
|
// Accept the data packet from client and verification
|
||||||
connfd = accept(sockfd, (SA*)&cli, &len);
|
connfd = accept(sockfd, (SA *)&cli, &len);
|
||||||
if (connfd < 0) {
|
if (connfd < 0)
|
||||||
printf("server acccept failed...\n");
|
{
|
||||||
exit(0);
|
printf("server acccept failed...\n");
|
||||||
}
|
exit(0);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
printf("server acccept the client...\n");
|
printf("server acccept the client...\n");
|
||||||
|
|
||||||
// Function for chatting between client and server
|
// Function for chatting between client and server
|
||||||
func(connfd);
|
func(connfd);
|
||||||
|
|
||||||
// After chatting close the socket
|
// After chatting close the socket
|
||||||
close(sockfd);
|
close(sockfd);
|
||||||
}
|
}
|
||||||
|
@ -1,25 +1,26 @@
|
|||||||
/**
|
/**
|
||||||
* Modified 07/12/2017, Kyler Smith
|
* Modified 07/12/2017, Kyler Smith
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
int main() {
|
int main()
|
||||||
|
{
|
||||||
|
|
||||||
int remainder, number = 0, decimal_number = 0, temp = 1;
|
int remainder, number = 0, decimal_number = 0, temp = 1;
|
||||||
printf("/n Enter any binary number= ");
|
printf("/n Enter any binary number= ");
|
||||||
scanf("%d", &number);
|
scanf("%d", &number);
|
||||||
|
|
||||||
// Iterate over the number until the end.
|
// 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);
|
remainder = number % 10;
|
||||||
|
number = number / 10;
|
||||||
|
decimal_number += remainder * temp;
|
||||||
|
temp = temp * 2; // used as power of 2
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d\n", decimal_number);
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
/*
|
/*
|
||||||
* C Program to Convert Binary to Hexadecimal
|
* C Program to Convert Binary to Hexadecimal
|
||||||
*/
|
*/
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
long int binary, hexa = 0, i = 1, remainder;
|
long int binary, hexa = 0, i = 1, remainder;
|
||||||
|
|
||||||
printf("Enter the binary number: ");
|
printf("Enter the binary number: ");
|
||||||
scanf("%ld", &binary);
|
scanf("%ld", &binary);
|
||||||
while (binary != 0)
|
while (binary != 0)
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
// Binary number to octal number conversion
|
// Binary number to octal number conversion
|
||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
//Function that returns the last three digits
|
// Function that returns the last three digits
|
||||||
int three_digits(int n)
|
int three_digits(int n)
|
||||||
{
|
{
|
||||||
int r, d = 0, p=1;
|
int r, d = 0, p = 1;
|
||||||
|
|
||||||
for(int i=0; i<3; i++)
|
for (int i = 0; i < 3; i++)
|
||||||
{
|
{
|
||||||
r = n%10;
|
r = n % 10;
|
||||||
d += r * p;
|
d += r * p;
|
||||||
p *= 10;
|
p *= 10;
|
||||||
n /= 10;
|
n /= 10;
|
||||||
@ -18,24 +18,26 @@ int three_digits(int n)
|
|||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
int binary_num, d=0, base=1, remainder, td, res=0, ord=1;
|
int binary_num, d = 0, base = 1, remainder, td, res = 0, ord = 1;
|
||||||
|
|
||||||
printf("Enter the binary no: ");
|
printf("Enter the binary no: ");
|
||||||
scanf("%d", &binary_num);
|
scanf("%d", &binary_num);
|
||||||
|
|
||||||
while(binary_num > 0)
|
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);
|
td = three_digits(binary_num);
|
||||||
|
|
||||||
else td = binary_num;
|
else
|
||||||
|
td = binary_num;
|
||||||
|
|
||||||
binary_num /= 1000;
|
binary_num /= 1000;
|
||||||
|
|
||||||
d = 0, base =1;
|
d = 0, base = 1;
|
||||||
|
|
||||||
// Converting the last three digits to decimal
|
// Converting the last three digits to decimal
|
||||||
while(td > 0)
|
while (td > 0)
|
||||||
{
|
{
|
||||||
remainder = td % 10;
|
remainder = td % 10;
|
||||||
td /= 10;
|
td /= 10;
|
||||||
|
@ -17,13 +17,13 @@ int main()
|
|||||||
|
|
||||||
// for the loops
|
// for the loops
|
||||||
int j;
|
int j;
|
||||||
int i=0;
|
int i = 0;
|
||||||
|
|
||||||
printf("\t\tConverter decimal --> binary\n\n");
|
printf("\t\tConverter decimal --> binary\n\n");
|
||||||
|
|
||||||
// reads a decimal number from the user.
|
// reads a decimal number from the user.
|
||||||
printf("\nenter a positive integer number: ");
|
printf("\nenter a positive integer number: ");
|
||||||
scanf("%d",&inputNumber);
|
scanf("%d", &inputNumber);
|
||||||
|
|
||||||
// make sure the input number is a positive integer.
|
// make sure the input number is a positive integer.
|
||||||
if (inputNumber < 0)
|
if (inputNumber < 0)
|
||||||
@ -33,7 +33,7 @@ int main()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// actual processing
|
// actual processing
|
||||||
while(inputNumber>0)
|
while (inputNumber > 0)
|
||||||
{
|
{
|
||||||
|
|
||||||
// computes the remainder by modulo 2
|
// computes the remainder by modulo 2
|
||||||
@ -44,15 +44,14 @@ int main()
|
|||||||
|
|
||||||
bits[i] = re;
|
bits[i] = re;
|
||||||
i++;
|
i++;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("\n the number in binary is: ");
|
printf("\n the number in binary is: ");
|
||||||
|
|
||||||
// iterates backwards over all bits
|
// iterates backwards over all bits
|
||||||
for(j=i-1; j>=0; j--)
|
for (j = i - 1; j >= 0; j--)
|
||||||
{
|
{
|
||||||
printf("%d",bits[j]);
|
printf("%d", bits[j]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// for the case the input number is 0
|
// for the case the input number is 0
|
||||||
@ -63,4 +62,3 @@ int main()
|
|||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,45 +2,50 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
void decimal2Hexadecimal(long num);
|
void decimal2Hexadecimal(long num);
|
||||||
|
|
||||||
|
int main()
|
||||||
int main(){
|
{
|
||||||
|
|
||||||
long decimalnum;
|
|
||||||
|
|
||||||
printf("Enter decimal number: ");
|
|
||||||
scanf("%ld", &decimalnum);
|
|
||||||
|
|
||||||
decimal2Hexadecimal(decimalnum);
|
|
||||||
|
|
||||||
return 0;
|
long decimalnum;
|
||||||
|
|
||||||
|
printf("Enter decimal number: ");
|
||||||
|
scanf("%ld", &decimalnum);
|
||||||
|
|
||||||
|
decimal2Hexadecimal(decimalnum);
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/********function for convert decimal number to hexadecimal number****************/
|
/********function for convert decimal number to hexadecimal
|
||||||
void decimal2Hexadecimal(long num){
|
* number****************/
|
||||||
|
void decimal2Hexadecimal(long num)
|
||||||
|
{
|
||||||
|
|
||||||
long decimalnum=num;
|
long decimalnum = num;
|
||||||
long quotient, remainder;
|
long quotient, remainder;
|
||||||
int i, j = 0;
|
int i, j = 0;
|
||||||
char hexadecimalnum[100];
|
char hexadecimalnum[100];
|
||||||
|
|
||||||
quotient = decimalnum;
|
quotient = decimalnum;
|
||||||
|
|
||||||
while (quotient != 0){
|
while (quotient != 0)
|
||||||
|
{
|
||||||
|
|
||||||
remainder = quotient % 16;
|
remainder = quotient % 16;
|
||||||
if (remainder < 10)
|
if (remainder < 10)
|
||||||
hexadecimalnum[j++] = 48 + remainder;
|
hexadecimalnum[j++] = 48 + remainder;
|
||||||
|
|
||||||
else
|
else
|
||||||
hexadecimalnum[j++] = 55 + remainder;
|
hexadecimalnum[j++] = 55 + remainder;
|
||||||
|
|
||||||
quotient = quotient / 16;}
|
quotient = quotient / 16;
|
||||||
|
}
|
||||||
|
|
||||||
// print the hexadecimal number
|
// print the hexadecimal number
|
||||||
|
|
||||||
for (i = j; i >= 0; i--){
|
for (i = j; i >= 0; i--)
|
||||||
printf("%c", hexadecimalnum[i]);}
|
{
|
||||||
|
printf("%c", hexadecimalnum[i]);
|
||||||
|
}
|
||||||
|
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,35 +1,38 @@
|
|||||||
/*****Decimal to octal conversion*******************/
|
/*****Decimal to octal conversion*******************/
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
void decimal2Octal(long decimalnum);
|
void decimal2Octal(long decimalnum);
|
||||||
|
|
||||||
int main(){
|
int main()
|
||||||
|
{
|
||||||
|
|
||||||
long decimalnum;
|
long decimalnum;
|
||||||
|
|
||||||
printf("Enter the decimal number: ");
|
printf("Enter the decimal number: ");
|
||||||
scanf("%ld", &decimalnum);
|
scanf("%ld", &decimalnum);
|
||||||
|
|
||||||
decimal2Octal(decimalnum);
|
decimal2Octal(decimalnum);
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/********function for convert decimal numbers to octal numbers************/
|
/********function for convert decimal numbers to octal numbers************/
|
||||||
void decimal2Octal(long decimalnum){
|
void decimal2Octal(long decimalnum)
|
||||||
long remainder, quotient;
|
{
|
||||||
|
long remainder, quotient;
|
||||||
|
|
||||||
int octalNumber[100], i = 1, j;
|
int octalNumber[100], i = 1, j;
|
||||||
quotient = decimalnum;
|
quotient = decimalnum;
|
||||||
|
|
||||||
while (quotient != 0){
|
while (quotient != 0)
|
||||||
octalNumber[i++] = quotient % 8;
|
{
|
||||||
|
octalNumber[i++] = quotient % 8;
|
||||||
|
|
||||||
quotient = quotient / 8;
|
quotient = quotient / 8;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (j = i - 1; j > 0; j--)
|
for (j = i - 1; j > 0; j--)
|
||||||
|
|
||||||
printf("%d", octalNumber[j]);
|
printf("%d", octalNumber[j]);
|
||||||
|
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
@ -1,29 +1,29 @@
|
|||||||
//Program to convert decimal number to octal (Using Reccursion)
|
// Program to convert decimal number to octal (Using Reccursion)
|
||||||
//This program only works for integer decimals
|
// This program only works for integer decimals
|
||||||
//Created by Aromal Anil
|
// Created by Aromal Anil
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
int decimal_to_octal(int decimal)
|
int decimal_to_octal(int decimal)
|
||||||
{
|
{
|
||||||
if ((decimal < 8) && (decimal > 0))
|
if ((decimal < 8) && (decimal > 0))
|
||||||
{
|
{
|
||||||
return decimal;
|
return decimal;
|
||||||
}
|
}
|
||||||
else if (decimal == 0)
|
else if (decimal == 0)
|
||||||
{
|
{
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8);
|
return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int octalNumber, decimalNumber;
|
int octalNumber, decimalNumber;
|
||||||
printf("\nEnter your decimal number : ");
|
printf("\nEnter your decimal number : ");
|
||||||
scanf("%d", &decimalNumber);
|
scanf("%d", &decimalNumber);
|
||||||
octalNumber = decimal_to_octal(decimalNumber);
|
octalNumber = decimal_to_octal(decimalNumber);
|
||||||
printf("\nThe octal of %d is : %d", decimalNumber, octalNumber);
|
printf("\nThe octal of %d is : %d", decimalNumber, octalNumber);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -2,15 +2,15 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
// Converts octal number to decimal
|
// Converts octal number to decimal
|
||||||
int convertValue(int num, int i) {
|
int convertValue(int num, int i) { return num * pow(8, i); }
|
||||||
return num * pow(8, i);
|
|
||||||
}
|
|
||||||
|
|
||||||
long long toDecimal(int octal_value) {
|
long long toDecimal(int octal_value)
|
||||||
|
{
|
||||||
|
|
||||||
int decimal_value = 0, i = 0;
|
int decimal_value = 0, i = 0;
|
||||||
|
|
||||||
while (octal_value) {
|
while (octal_value)
|
||||||
|
{
|
||||||
|
|
||||||
// Extracts right-most digit and then multiplies by 8^i
|
// Extracts right-most digit and then multiplies by 8^i
|
||||||
decimal_value += convertValue(octal_value % 10, i++);
|
decimal_value += convertValue(octal_value % 10, i++);
|
||||||
@ -22,7 +22,8 @@ long long toDecimal(int octal_value) {
|
|||||||
return decimal_value;
|
return decimal_value;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
int main()
|
||||||
|
{
|
||||||
|
|
||||||
printf("Enter octal value: ");
|
printf("Enter octal value: ");
|
||||||
|
|
||||||
|
@ -2,39 +2,43 @@
|
|||||||
* convert from any base to decimal
|
* convert from any base to decimal
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <ctype.h>
|
#include <ctype.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
int main(void) {
|
int main(void)
|
||||||
int base, i, j;
|
{
|
||||||
char number[100];
|
int base, i, j;
|
||||||
unsigned long decimal = 0;
|
char number[100];
|
||||||
|
unsigned long decimal = 0;
|
||||||
printf("Enter the base: ");
|
|
||||||
scanf("%d", &base);
|
printf("Enter the base: ");
|
||||||
printf("Enter the number: ");
|
scanf("%d", &base);
|
||||||
scanf("%s", &number[0]);
|
printf("Enter the number: ");
|
||||||
|
scanf("%s", &number[0]);
|
||||||
for (i = 0; number[i] != '\0'; i++) {
|
|
||||||
if (isdigit(number[i]))
|
for (i = 0; number[i] != '\0'; i++)
|
||||||
number[i] -= '0';
|
{
|
||||||
else if (isupper(number[i]))
|
if (isdigit(number[i]))
|
||||||
number[i] -= 'A' - 10;
|
number[i] -= '0';
|
||||||
else if (islower(number[i]))
|
else if (isupper(number[i]))
|
||||||
number[i] -= 'a' - 10;
|
number[i] -= 'A' - 10;
|
||||||
else
|
else if (islower(number[i]))
|
||||||
number[i] = base + 1;
|
number[i] -= 'a' - 10;
|
||||||
|
else
|
||||||
if (number[i] >= base){
|
number[i] = base + 1;
|
||||||
printf("invalid number\n");
|
|
||||||
return 0;
|
if (number[i] >= base)
|
||||||
}
|
{
|
||||||
}
|
printf("invalid number\n");
|
||||||
|
return 0;
|
||||||
for (j = 0; j < i; j++) {
|
}
|
||||||
decimal *= base;
|
}
|
||||||
decimal += number[j];
|
|
||||||
}
|
for (j = 0; j < i; j++)
|
||||||
|
{
|
||||||
printf("%lu\n", decimal);
|
decimal *= base;
|
||||||
|
decimal += number[j];
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%lu\n", decimal);
|
||||||
}
|
}
|
||||||
|
@ -13,243 +13,276 @@
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Return Codes
|
Return Codes
|
||||||
|
|
||||||
-1 - Array Erased
|
-1 - Array Erased
|
||||||
0 - Success
|
0 - Success
|
||||||
1 - Invalid Position
|
1 - Invalid Position
|
||||||
2 - Position already initialized (use update function)
|
2 - Position already initialized (use update function)
|
||||||
3 - Position not initialized (use insert function)
|
3 - Position not initialized (use insert function)
|
||||||
4 - Position already empty
|
4 - Position already empty
|
||||||
5 - Array is full
|
5 - Array is full
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include "CArray.h"
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include "CArray.h"
|
|
||||||
|
|
||||||
void swap(CArray *array, int position1, int position2);
|
void swap(CArray *array, int position1, int position2);
|
||||||
|
|
||||||
CArray * getCArray(int size)
|
CArray *getCArray(int size)
|
||||||
{
|
{
|
||||||
CArray *array = (CArray *) malloc(sizeof(CArray));
|
CArray *array = (CArray *)malloc(sizeof(CArray));
|
||||||
array->array = (int *) malloc(sizeof(int) * size);
|
array->array = (int *)malloc(sizeof(int) * size);
|
||||||
array->size = size;
|
array->size = size;
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < size; i++) {
|
for (i = 0; i < size; i++)
|
||||||
array->array[i] = 0;
|
{
|
||||||
}
|
array->array[i] = 0;
|
||||||
return array;
|
}
|
||||||
|
return array;
|
||||||
}
|
}
|
||||||
|
|
||||||
int insertValueCArray(CArray *array, int position, int value)
|
int insertValueCArray(CArray *array, int position, int value)
|
||||||
{
|
{
|
||||||
if (position >= 0 && position < array->size) {
|
if (position >= 0 && position < array->size)
|
||||||
if (array->array[position] == 0) {
|
{
|
||||||
array->array[position] = value;
|
if (array->array[position] == 0)
|
||||||
return SUCCESS;
|
{
|
||||||
}
|
array->array[position] = value;
|
||||||
else return POSITION_INIT;
|
return SUCCESS;
|
||||||
}
|
}
|
||||||
return INVALID_POSITION;
|
else
|
||||||
|
return POSITION_INIT;
|
||||||
|
}
|
||||||
|
return INVALID_POSITION;
|
||||||
}
|
}
|
||||||
|
|
||||||
int removeValueCArray(CArray *array, int position)
|
int removeValueCArray(CArray *array, int position)
|
||||||
{
|
{
|
||||||
if (position >= 0 && position < array->size) {
|
if (position >= 0 && position < array->size)
|
||||||
if (array->array[position] != 0) {
|
{
|
||||||
array->array[position] = 0;
|
if (array->array[position] != 0)
|
||||||
}
|
{
|
||||||
else return POSITION_EMPTY;
|
array->array[position] = 0;
|
||||||
}
|
}
|
||||||
return INVALID_POSITION;
|
else
|
||||||
|
return POSITION_EMPTY;
|
||||||
|
}
|
||||||
|
return INVALID_POSITION;
|
||||||
}
|
}
|
||||||
|
|
||||||
int pushValueCArray(CArray *array, int value)
|
int pushValueCArray(CArray *array, int value)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
int ok = 0;
|
int ok = 0;
|
||||||
for (i = 0; i < array->size; i++) {
|
for (i = 0; i < array->size; i++)
|
||||||
if (array->array[i] == 0) {
|
{
|
||||||
array->array[i] = value;
|
if (array->array[i] == 0)
|
||||||
ok = 1;
|
{
|
||||||
break;
|
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)
|
int updateValueCArray(CArray *array, int position, int value)
|
||||||
{
|
{
|
||||||
if (position >= 0 && position < array->size) {
|
if (position >= 0 && position < array->size)
|
||||||
if (array->array[position] != 0) {
|
{
|
||||||
|
if (array->array[position] != 0)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
}
|
else
|
||||||
|
return POSITION_NOT_INIT;
|
||||||
else return POSITION_NOT_INIT;
|
}
|
||||||
}
|
return INVALID_POSITION;
|
||||||
return INVALID_POSITION;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int eraseCArray(CArray *array)
|
int eraseCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < array->size; i++) {
|
for (i = 0; i < array->size; i++)
|
||||||
array->array[i] = 0;
|
{
|
||||||
}
|
array->array[i] = 0;
|
||||||
return 0;
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int switchValuesCArray(CArray *array, int position1, int position2)
|
int switchValuesCArray(CArray *array, int position1, int position2)
|
||||||
{
|
{
|
||||||
if (position1 >= 0 && position1 < array->size
|
if (position1 >= 0 && position1 < array->size && position2 >= 0 &&
|
||||||
&& position2 >= 0 && position2 < array->size) {
|
position2 < array->size)
|
||||||
int temp = array->array[position1];
|
{
|
||||||
array->array[position1] = array->array[position2];
|
int temp = array->array[position1];
|
||||||
array->array[position2] = temp;
|
array->array[position1] = array->array[position2];
|
||||||
}
|
array->array[position2] = temp;
|
||||||
return INVALID_POSITION;
|
}
|
||||||
|
return INVALID_POSITION;
|
||||||
}
|
}
|
||||||
|
|
||||||
int reverseCArray(CArray *array)
|
int reverseCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i;
|
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);
|
{
|
||||||
}
|
swap(array, i, array->size - i - 1);
|
||||||
return SUCCESS;
|
}
|
||||||
|
return SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
int displayCArray(CArray *array)
|
int displayCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
printf("\nC ARRAY\n");
|
printf("\nC ARRAY\n");
|
||||||
for (i = 0; i < array->size; i++) {
|
for (i = 0; i < array->size; i++)
|
||||||
printf("%d ", array->array[i]);
|
{
|
||||||
}
|
printf("%d ", array->array[i]);
|
||||||
printf("\n");
|
}
|
||||||
return 0;
|
printf("\n");
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int blenderCArray(CArray *array)
|
int blenderCArray(CArray *array)
|
||||||
{
|
{
|
||||||
srand(time(NULL) * array->size);
|
srand(time(NULL) * array->size);
|
||||||
int i;
|
int i;
|
||||||
int total = array->size * 100;
|
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);
|
{
|
||||||
}
|
swap(array, rand() % array->size, rand() % array->size);
|
||||||
return 0;
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
CArray * getCopyCArray(CArray *arr)
|
CArray *getCopyCArray(CArray *arr)
|
||||||
{
|
{
|
||||||
CArray *array = (CArray *)malloc(sizeof(CArray));
|
CArray *array = (CArray *)malloc(sizeof(CArray));
|
||||||
array->array = (int *)malloc(sizeof(int) * arr->size);
|
array->array = (int *)malloc(sizeof(int) * arr->size);
|
||||||
array->size = arr->size;
|
array->size = arr->size;
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < arr->size; i++) {
|
for (i = 0; i < arr->size; i++)
|
||||||
array->array[i] = arr->array[i];
|
{
|
||||||
}
|
array->array[i] = arr->array[i];
|
||||||
return array;
|
}
|
||||||
|
return array;
|
||||||
}
|
}
|
||||||
|
|
||||||
void swap(CArray *array, int position1, int position2)
|
void swap(CArray *array, int position1, int position2)
|
||||||
{
|
{
|
||||||
int temp = array->array[position1];
|
int temp = array->array[position1];
|
||||||
array->array[position1] = array->array[position2];
|
array->array[position1] = array->array[position2];
|
||||||
array->array[position2] = temp;
|
array->array[position2] = temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
int bubbleSortCArray(CArray *array)
|
int bubbleSortCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i, j;
|
int i, j;
|
||||||
for (i = 0; i < array->size - 1; i++) {
|
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 (j = 0; j < array->size - i - 1; j++)
|
||||||
swap(array, j, j + 1);
|
{
|
||||||
}
|
if (array->array[j] > array->array[j + 1])
|
||||||
}
|
{
|
||||||
}
|
swap(array, j, j + 1);
|
||||||
return 0;
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int selectionSortCArray(CArray *array)
|
int selectionSortCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i, j, min;
|
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++)
|
min = i;
|
||||||
if (array->array[j] < array->array[min]) min = j;
|
for (j = i + 1; j < array->size; j++)
|
||||||
swap(array, min, i);
|
if (array->array[j] < array->array[min])
|
||||||
}
|
min = j;
|
||||||
return 0;
|
swap(array, min, i);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int insertionSortCArray(CArray *array)
|
int insertionSortCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i, j, num;
|
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;
|
num = array->array[i];
|
||||||
while (j >= 0 && array->array[j] > num)
|
j = i - 1;
|
||||||
{
|
while (j >= 0 && array->array[j] > num)
|
||||||
array->array[j + 1] = array->array[j];
|
{
|
||||||
j--;
|
array->array[j + 1] = array->array[j];
|
||||||
}
|
j--;
|
||||||
array->array[j + 1] = num;
|
}
|
||||||
}
|
array->array[j + 1] = num;
|
||||||
return 0;
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int valueOcurranceCArray(CArray *array, int value)
|
int valueOcurranceCArray(CArray *array, int value)
|
||||||
{
|
{
|
||||||
int i, total = 0;
|
int i, total = 0;
|
||||||
for (i = 0; i < array->size; i++) {
|
for (i = 0; i < array->size; i++)
|
||||||
if (array->array[i] == value) total++;
|
{
|
||||||
}
|
if (array->array[i] == value)
|
||||||
return total;
|
total++;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
}
|
}
|
||||||
|
|
||||||
CArray * valuePositionsCArray(CArray *array, int value)
|
CArray *valuePositionsCArray(CArray *array, int value)
|
||||||
{
|
{
|
||||||
int i, j = 0;
|
int i, j = 0;
|
||||||
int total = valueOcurranceCArray(array, value);
|
int total = valueOcurranceCArray(array, value);
|
||||||
CArray *resultArray = getCArray(total);
|
CArray *resultArray = getCArray(total);
|
||||||
for (i = 0; i < array->size; i++) {
|
for (i = 0; i < array->size; i++)
|
||||||
if (array->array[i] == value) {
|
{
|
||||||
// Hopefully this won't overflow
|
if (array->array[i] == value)
|
||||||
resultArray->array[j] = i;
|
{
|
||||||
j++;
|
// Hopefully this won't overflow
|
||||||
}
|
resultArray->array[j] = i;
|
||||||
}
|
j++;
|
||||||
return resultArray;
|
}
|
||||||
|
}
|
||||||
|
return resultArray;
|
||||||
}
|
}
|
||||||
|
|
||||||
int findMinCArray(CArray *array)
|
int findMinCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
int min = array->array[0];
|
int min = array->array[0];
|
||||||
for (i = 1; i < array->size; i++) {
|
for (i = 1; i < array->size; i++)
|
||||||
if (array->array[i] < min) {
|
{
|
||||||
min = array->array[i];
|
if (array->array[i] < min)
|
||||||
}
|
{
|
||||||
}
|
min = array->array[i];
|
||||||
return min;
|
}
|
||||||
|
}
|
||||||
|
return min;
|
||||||
}
|
}
|
||||||
|
|
||||||
int findMaxCArray(CArray *array)
|
int findMaxCArray(CArray *array)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
int max = array->array[0];
|
int max = array->array[0];
|
||||||
for (i = 1; i < array->size; i++) {
|
for (i = 1; i < array->size; i++)
|
||||||
if (array->array[i] > max) {
|
{
|
||||||
max = array->array[i];
|
if (array->array[i] > max)
|
||||||
}
|
{
|
||||||
}
|
max = array->array[i];
|
||||||
return max;
|
}
|
||||||
|
}
|
||||||
|
return max;
|
||||||
}
|
}
|
||||||
|
@ -16,68 +16,69 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#ifdef __cplusplus
|
#ifdef __cplusplus
|
||||||
extern "C" {
|
extern "C"
|
||||||
|
{
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define ARRAY_ERASED -1
|
#define ARRAY_ERASED -1
|
||||||
#define SUCCESS 0
|
#define SUCCESS 0
|
||||||
#define INVALID_POSITION 1
|
#define INVALID_POSITION 1
|
||||||
#define POSITION_INIT 2
|
#define POSITION_INIT 2
|
||||||
#define POSITION_NOT_INIT 3
|
#define POSITION_NOT_INIT 3
|
||||||
#define POSITION_EMPTY 4
|
#define POSITION_EMPTY 4
|
||||||
#define ARRAY_FULL 5
|
#define ARRAY_FULL 5
|
||||||
|
|
||||||
typedef struct CArray {
|
typedef struct CArray
|
||||||
int *array;
|
{
|
||||||
int size;
|
int *array;
|
||||||
} CArray;
|
int size;
|
||||||
|
} CArray;
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Returns array |
|
// | Returns array |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
CArray * getCArray(int size);
|
CArray *getCArray(int size);
|
||||||
CArray * getCopyCArray(CArray *array);
|
CArray *getCopyCArray(CArray *array);
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Input / Output |
|
// | Input / Output |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
int insertValueCArray(CArray *array, int position, int value);
|
int insertValueCArray(CArray *array, int position, int value);
|
||||||
int removeValueCArray(CArray *array, int position);
|
int removeValueCArray(CArray *array, int position);
|
||||||
int pushValueCArray(CArray *array, int value);
|
int pushValueCArray(CArray *array, int value);
|
||||||
int updateValueCArray(CArray *array, int position, int value);
|
int updateValueCArray(CArray *array, int position, int value);
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Erase |
|
// | Erase |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
int eraseCArray(CArray *array);
|
int eraseCArray(CArray *array);
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Switching |
|
// | Switching |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
int switchValuesCArray(CArray *array, int position1, int position2);
|
int switchValuesCArray(CArray *array, int position1, int position2);
|
||||||
int reverseCArray(CArray *array);
|
int reverseCArray(CArray *array);
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Sorting |
|
// | Sorting |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
int bubbleSortCArray(CArray *array);
|
int bubbleSortCArray(CArray *array);
|
||||||
int selectionSortCArray(CArray *array);
|
int selectionSortCArray(CArray *array);
|
||||||
int insertionSortCArray(CArray *array);
|
int insertionSortCArray(CArray *array);
|
||||||
int blenderCArray(CArray *array);
|
int blenderCArray(CArray *array);
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Searching |
|
// | Searching |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
int valueOcurranceCArray(CArray *array, int value);
|
int valueOcurranceCArray(CArray *array, int value);
|
||||||
CArray * valuePositionsCArray(CArray *array, int value);
|
CArray *valuePositionsCArray(CArray *array, int value);
|
||||||
int findMaxCArray(CArray *array);
|
int findMaxCArray(CArray *array);
|
||||||
int findMinCArray(CArray *array);
|
int findMinCArray(CArray *array);
|
||||||
|
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
// | Display |
|
// | Display |
|
||||||
// +-------------------------------------+
|
// +-------------------------------------+
|
||||||
int displayCArray(CArray *array);
|
int displayCArray(CArray *array);
|
||||||
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
#ifdef __cplusplus
|
||||||
}
|
}
|
||||||
|
@ -13,140 +13,148 @@
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include "CArray.h"
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include "CArray.h"
|
|
||||||
|
|
||||||
int CArrayTests()
|
int CArrayTests()
|
||||||
{
|
{
|
||||||
printf("\n");
|
printf("\n");
|
||||||
printf(" +-------------------------------------+\n");
|
printf(" +-------------------------------------+\n");
|
||||||
printf(" | |\n");
|
printf(" | |\n");
|
||||||
printf(" | C Array |\n");
|
printf(" | C Array |\n");
|
||||||
printf(" | |\n");
|
printf(" | |\n");
|
||||||
printf(" +-------------------------------------+\n");
|
printf(" +-------------------------------------+\n");
|
||||||
printf("\n");
|
printf("\n");
|
||||||
|
|
||||||
CArray *array = getCArray(10);
|
CArray *array = getCArray(10);
|
||||||
|
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < array->size; i++) {
|
for (i = 0; i < array->size; i++)
|
||||||
insertValueCArray(array, i, i+1);
|
{
|
||||||
}
|
insertValueCArray(array, i, i + 1);
|
||||||
printf("Entered array is:\n");
|
}
|
||||||
displayCArray(array);
|
printf("Entered array is:\n");
|
||||||
printf("\nCode: %d\n", pushValueCArray(array, 11)); // 5
|
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);
|
{
|
||||||
}
|
removeValueCArray(array, i);
|
||||||
|
}
|
||||||
displayCArray(array);
|
|
||||||
|
|
||||||
printf("\nCode: %d", removeValueCArray(array, -1)); // 1
|
displayCArray(array);
|
||||||
printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1
|
|
||||||
|
|
||||||
// Erase
|
printf("\nCode: %d", removeValueCArray(array, -1)); // 1
|
||||||
for (i = 0; i < array->size; i++) {
|
printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1
|
||||||
insertValueCArray(array, i, i + 1);
|
|
||||||
}
|
|
||||||
eraseCArray(array);
|
|
||||||
displayCArray(array); // Should give all 0s
|
|
||||||
|
|
||||||
// Switching
|
// Erase
|
||||||
CArray *arr = getCArray(13);
|
for (i = 0; i < array->size; i++)
|
||||||
for (i = 0; i < arr->size; i++) {
|
{
|
||||||
insertValueCArray(arr, i, i + 1);
|
insertValueCArray(array, i, i + 1);
|
||||||
}
|
}
|
||||||
displayCArray(arr);
|
eraseCArray(array);
|
||||||
for (i = 0; i < arr->size / 2; i++) {
|
displayCArray(array); // Should give all 0s
|
||||||
switchValuesCArray(arr, i, arr->size - i - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
displayCArray(arr);
|
// Switching
|
||||||
|
CArray *arr = getCArray(13);
|
||||||
|
for (i = 0; i < arr->size; i++)
|
||||||
|
{
|
||||||
|
insertValueCArray(arr, i, i + 1);
|
||||||
|
}
|
||||||
|
displayCArray(arr);
|
||||||
|
for (i = 0; i < arr->size / 2; i++)
|
||||||
|
{
|
||||||
|
switchValuesCArray(arr, i, arr->size - i - 1);
|
||||||
|
}
|
||||||
|
|
||||||
// Or simply...
|
displayCArray(arr);
|
||||||
reverseCArray(arr);
|
|
||||||
|
|
||||||
displayCArray(arr);
|
// Or simply...
|
||||||
|
reverseCArray(arr);
|
||||||
// Sorting
|
|
||||||
srand(time(NULL));
|
|
||||||
CArray *barray = getCArray(20);
|
|
||||||
for (i = 0; i < barray->size; i++) {
|
|
||||||
insertValueCArray(barray, i, rand());
|
|
||||||
}
|
|
||||||
CArray *carray = getCopyCArray(barray);
|
|
||||||
CArray *darray = getCopyCArray(barray);
|
|
||||||
printf("\nNot sorted Array:");
|
|
||||||
displayCArray(barray);
|
|
||||||
|
|
||||||
printf("\nBubble Sort:");
|
displayCArray(arr);
|
||||||
clock_t begin1 = clock();
|
|
||||||
// Timing bubble sort
|
|
||||||
bubbleSortCArray(barray);
|
|
||||||
clock_t end1 = clock();
|
|
||||||
double time_spent1 = (double)(end1 - begin1) / CLOCKS_PER_SEC;
|
|
||||||
displayCArray(barray);
|
|
||||||
|
|
||||||
printf("\nSelection Sort:");
|
// Sorting
|
||||||
clock_t begin2 = clock();
|
srand(time(NULL));
|
||||||
// Timing selection sort
|
CArray *barray = getCArray(20);
|
||||||
selectionSortCArray(carray);
|
for (i = 0; i < barray->size; i++)
|
||||||
clock_t end2 = clock();
|
{
|
||||||
double time_spent2 = (double)(end2 - begin2) / CLOCKS_PER_SEC;
|
insertValueCArray(barray, i, rand());
|
||||||
displayCArray(carray);
|
}
|
||||||
|
CArray *carray = getCopyCArray(barray);
|
||||||
|
CArray *darray = getCopyCArray(barray);
|
||||||
|
printf("\nNot sorted Array:");
|
||||||
|
displayCArray(barray);
|
||||||
|
|
||||||
printf("\nInsertion Sort:");
|
printf("\nBubble Sort:");
|
||||||
clock_t begin3 = clock();
|
clock_t begin1 = clock();
|
||||||
// Timing insertion sort
|
// Timing bubble sort
|
||||||
insertionSortCArray(darray);
|
bubbleSortCArray(barray);
|
||||||
clock_t end3 = clock();
|
clock_t end1 = clock();
|
||||||
double time_spent3 = (double)(end3 - begin3) / CLOCKS_PER_SEC;
|
double time_spent1 = (double)(end1 - begin1) / CLOCKS_PER_SEC;
|
||||||
displayCArray(carray);
|
displayCArray(barray);
|
||||||
|
|
||||||
// Descending order
|
printf("\nSelection Sort:");
|
||||||
reverseCArray(barray);
|
clock_t begin2 = clock();
|
||||||
// displayCArray(barray);
|
// Timing selection sort
|
||||||
|
selectionSortCArray(carray);
|
||||||
|
clock_t end2 = clock();
|
||||||
|
double time_spent2 = (double)(end2 - begin2) / CLOCKS_PER_SEC;
|
||||||
|
displayCArray(carray);
|
||||||
|
|
||||||
// printf("\nBlender:");
|
printf("\nInsertion Sort:");
|
||||||
// blenderCArray(barray);
|
clock_t begin3 = clock();
|
||||||
// displayCArray(barray);
|
// Timing insertion sort
|
||||||
|
insertionSortCArray(darray);
|
||||||
|
clock_t end3 = clock();
|
||||||
|
double time_spent3 = (double)(end3 - begin3) / CLOCKS_PER_SEC;
|
||||||
|
displayCArray(carray);
|
||||||
|
|
||||||
printf("\nTotal time spent for bubble sort: %lf seconds", time_spent1);
|
// Descending order
|
||||||
printf("\nTotal time spent for selection sort: %lf seconds", time_spent2);
|
reverseCArray(barray);
|
||||||
printf("\nTotal time spent for insertion sort: %lf seconds", time_spent3);
|
// displayCArray(barray);
|
||||||
|
|
||||||
// Searching
|
// printf("\nBlender:");
|
||||||
CArray *aarray = getCArray(1000);
|
// blenderCArray(barray);
|
||||||
for (i = 0; i < aarray->size; i++) {
|
// displayCArray(barray);
|
||||||
insertValueCArray(aarray, i, rand() % 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
int j = 24;
|
printf("\nTotal time spent for bubble sort: %lf seconds", time_spent1);
|
||||||
printf("\nOccurrences of the number %d in the array: %d", j,
|
printf("\nTotal time spent for selection sort: %lf seconds", time_spent2);
|
||||||
valueOcurranceCArray(aarray, j));
|
printf("\nTotal time spent for insertion sort: %lf seconds", time_spent3);
|
||||||
printf("\nAnd its positions:\n");
|
|
||||||
CArray *positions = valuePositionsCArray(aarray, j);
|
|
||||||
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]]);
|
|
||||||
}
|
|
||||||
printf("\nThe list has a minimum value of %d and a maximum value of %d",
|
|
||||||
findMinCArray(aarray), findMaxCArray(aarray));
|
|
||||||
insertionSortCArray(aarray);
|
|
||||||
// displayCArray(aarray);
|
|
||||||
|
|
||||||
free(arr);
|
// Searching
|
||||||
free(array);
|
CArray *aarray = getCArray(1000);
|
||||||
free(aarray);
|
for (i = 0; i < aarray->size; i++)
|
||||||
free(barray);
|
{
|
||||||
free(carray);
|
insertValueCArray(aarray, i, rand() % 100);
|
||||||
free(darray);
|
}
|
||||||
printf("\n");
|
|
||||||
return 0;
|
int j = 24;
|
||||||
|
printf("\nOccurrences of the number %d in the array: %d", j,
|
||||||
|
valueOcurranceCArray(aarray, j));
|
||||||
|
printf("\nAnd its positions:\n");
|
||||||
|
CArray *positions = valuePositionsCArray(aarray, j);
|
||||||
|
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]]);
|
||||||
|
}
|
||||||
|
printf("\nThe list has a minimum value of %d and a maximum value of %d",
|
||||||
|
findMinCArray(aarray), findMaxCArray(aarray));
|
||||||
|
insertionSortCArray(aarray);
|
||||||
|
// displayCArray(aarray);
|
||||||
|
|
||||||
|
free(arr);
|
||||||
|
free(array);
|
||||||
|
free(aarray);
|
||||||
|
free(barray);
|
||||||
|
free(carray);
|
||||||
|
free(darray);
|
||||||
|
printf("\n");
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -3,429 +3,422 @@
|
|||||||
|
|
||||||
struct AVLnode
|
struct AVLnode
|
||||||
{
|
{
|
||||||
int key;
|
int key;
|
||||||
struct AVLnode *left;
|
struct AVLnode *left;
|
||||||
struct AVLnode *right;
|
struct AVLnode *right;
|
||||||
int height;
|
int height;
|
||||||
};
|
};
|
||||||
typedef struct AVLnode avlNode;
|
typedef struct AVLnode avlNode;
|
||||||
|
|
||||||
int max(int a, int b)
|
int max(int a, int b) { return (a > b) ? a : b; }
|
||||||
{
|
|
||||||
return (a > b)? a : b;
|
|
||||||
}
|
|
||||||
|
|
||||||
avlNode *newNode(int key)
|
avlNode *newNode(int key)
|
||||||
{
|
{
|
||||||
avlNode *node = (avlNode*)malloc(sizeof(avlNode));
|
avlNode *node = (avlNode *)malloc(sizeof(avlNode));
|
||||||
|
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
printf("!! Out of Space !!\n");
|
printf("!! Out of Space !!\n");
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
node->key = key;
|
node->key = key;
|
||||||
node->left = NULL;
|
node->left = NULL;
|
||||||
node->right = NULL;
|
node->right = NULL;
|
||||||
node->height = 0;
|
node->height = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
int nodeHeight(avlNode *node)
|
int nodeHeight(avlNode *node)
|
||||||
{
|
{
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return -1;
|
return -1;
|
||||||
else
|
else
|
||||||
return(node->height);
|
return (node->height);
|
||||||
}
|
}
|
||||||
|
|
||||||
int heightDiff(avlNode *node)
|
int heightDiff(avlNode *node)
|
||||||
{
|
{
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return 0;
|
return 0;
|
||||||
else
|
else
|
||||||
return(nodeHeight(node->left) - nodeHeight(node->right));
|
return (nodeHeight(node->left) - nodeHeight(node->right));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Returns the node with min key in the left subtree*/
|
/* Returns the node with min key in the left subtree*/
|
||||||
avlNode *minNode(avlNode *node)
|
avlNode *minNode(avlNode *node)
|
||||||
{
|
{
|
||||||
avlNode *temp = node;
|
avlNode *temp = node;
|
||||||
|
|
||||||
while(temp->left != NULL)
|
while (temp->left != NULL)
|
||||||
temp = temp->left;
|
temp = temp->left;
|
||||||
|
|
||||||
return temp;
|
return temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printAVL(avlNode *node, int level)
|
void printAVL(avlNode *node, int level)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
if(node!=NULL)
|
if (node != NULL)
|
||||||
{
|
{
|
||||||
printAVL(node->right, level+1);
|
printAVL(node->right, level + 1);
|
||||||
printf("\n\n");
|
printf("\n\n");
|
||||||
|
|
||||||
for(i=0; i<level; i++)
|
for (i = 0; i < level; i++)
|
||||||
printf("\t");
|
printf("\t");
|
||||||
|
|
||||||
printf("%d", node->key);
|
printf("%d", node->key);
|
||||||
|
|
||||||
printAVL(node->left, level+1);
|
printAVL(node->left, level + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *rightRotate(avlNode *z)
|
avlNode *rightRotate(avlNode *z)
|
||||||
{
|
{
|
||||||
avlNode *y = z->left;
|
avlNode *y = z->left;
|
||||||
avlNode *T3 = y->right;
|
avlNode *T3 = y->right;
|
||||||
|
|
||||||
y->right = z;
|
y->right = z;
|
||||||
z->left = T3;
|
z->left = T3;
|
||||||
|
|
||||||
z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1);
|
z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1);
|
||||||
y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1);
|
y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1);
|
||||||
|
|
||||||
return y;
|
return y;
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *leftRotate(avlNode *z)
|
avlNode *leftRotate(avlNode *z)
|
||||||
{
|
{
|
||||||
avlNode *y = z->right;
|
avlNode *y = z->right;
|
||||||
avlNode *T3 = y->left;
|
avlNode *T3 = y->left;
|
||||||
|
|
||||||
y->left = z;
|
y->left = z;
|
||||||
z->right = T3;
|
z->right = T3;
|
||||||
|
|
||||||
z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1);
|
z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1);
|
||||||
y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1);
|
y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1);
|
||||||
|
|
||||||
return y;
|
return y;
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *LeftRightRotate(avlNode *z)
|
avlNode *LeftRightRotate(avlNode *z)
|
||||||
{
|
{
|
||||||
z->left = leftRotate(z->left);
|
z->left = leftRotate(z->left);
|
||||||
|
|
||||||
return (rightRotate(z));
|
return (rightRotate(z));
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *RightLeftRotate(avlNode *z)
|
avlNode *RightLeftRotate(avlNode *z)
|
||||||
{
|
{
|
||||||
z->right = rightRotate(z->right);
|
z->right = rightRotate(z->right);
|
||||||
|
|
||||||
return (leftRotate(z));
|
return (leftRotate(z));
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *insert(avlNode *node, int key)
|
avlNode *insert(avlNode *node, int key)
|
||||||
{
|
{
|
||||||
|
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return (newNode(key));
|
return (newNode(key));
|
||||||
|
|
||||||
/*Binary Search Tree insertion*/
|
/*Binary Search Tree insertion*/
|
||||||
|
|
||||||
if(key < node->key)
|
if (key < node->key)
|
||||||
node->left = insert(node->left, key); /*Recursive insertion in L subtree*/
|
node->left =
|
||||||
else if(key > node->key)
|
insert(node->left, key); /*Recursive insertion in L subtree*/
|
||||||
node->right = insert(node->right, key); /*Recursive insertion in R subtree*/
|
else if (key > node->key)
|
||||||
|
node->right =
|
||||||
|
insert(node->right, key); /*Recursive insertion in R subtree*/
|
||||||
|
|
||||||
/* Node Height as per the AVL formula*/
|
/* Node Height as per the AVL formula*/
|
||||||
node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1);
|
node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1);
|
||||||
|
|
||||||
|
/*Checking for the balance condition*/
|
||||||
|
int balance = heightDiff(node);
|
||||||
|
|
||||||
/*Checking for the balance condition*/
|
/*Left Left */
|
||||||
int balance = heightDiff(node);
|
if (balance > 1 && key < (node->left->key))
|
||||||
|
return rightRotate(node);
|
||||||
|
|
||||||
/*Left Left */
|
/*Right Right */
|
||||||
if(balance>1 && key < (node->left->key))
|
if (balance < -1 && key > (node->right->key))
|
||||||
return rightRotate(node);
|
return leftRotate(node);
|
||||||
|
|
||||||
/*Right Right */
|
/*Left Right */
|
||||||
if(balance<-1 && key > (node->right->key))
|
if (balance > 1 && key > (node->left->key))
|
||||||
return leftRotate(node);
|
{
|
||||||
|
node = LeftRightRotate(node);
|
||||||
|
}
|
||||||
|
|
||||||
/*Left Right */
|
/*Right Left */
|
||||||
if (balance>1 && key > (node->left->key))
|
if (balance < -1 && key < (node->right->key))
|
||||||
{
|
{
|
||||||
node = LeftRightRotate(node);
|
node = RightLeftRotate(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*Right Left */
|
|
||||||
if (balance<-1 && key < (node->right->key))
|
|
||||||
{
|
|
||||||
node = RightLeftRotate(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
return node;
|
|
||||||
|
|
||||||
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *delete(avlNode *node, int queryNum)
|
avlNode *delete (avlNode *node, int queryNum)
|
||||||
{
|
{
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return node;
|
return node;
|
||||||
|
|
||||||
if(queryNum < node->key)
|
if (queryNum < node->key)
|
||||||
node->left = delete(node->left, queryNum); /*Recursive deletion in L subtree*/
|
node->left =
|
||||||
else if(queryNum > node->key)
|
delete (node->left, queryNum); /*Recursive deletion in L subtree*/
|
||||||
node->right = delete(node->right, queryNum); /*Recursive deletion in R subtree*/
|
else if (queryNum > node->key)
|
||||||
else
|
node->right =
|
||||||
{
|
delete (node->right, queryNum); /*Recursive deletion in R subtree*/
|
||||||
/*Single or No Child*/
|
else
|
||||||
if((node->left == NULL) || (node->right==NULL))
|
{
|
||||||
{
|
/*Single or No Child*/
|
||||||
avlNode *temp = node->left ?
|
if ((node->left == NULL) || (node->right == NULL))
|
||||||
node->left :
|
{
|
||||||
node->right;
|
avlNode *temp = node->left ? node->left : node->right;
|
||||||
|
|
||||||
/* No Child*/
|
/* No Child*/
|
||||||
if(temp == NULL)
|
if (temp == NULL)
|
||||||
{
|
{
|
||||||
temp = node;
|
temp = node;
|
||||||
node = NULL;
|
node = NULL;
|
||||||
}
|
}
|
||||||
else /*Single Child : copy data to the parent*/
|
else /*Single Child : copy data to the parent*/
|
||||||
*node = *temp;
|
*node = *temp;
|
||||||
|
|
||||||
free(temp);
|
free(temp);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
/*Two Child*/
|
/*Two Child*/
|
||||||
|
|
||||||
/*Get the smallest key in the R subtree*/
|
/*Get the smallest key in the R subtree*/
|
||||||
avlNode *temp = minNode(node->right);
|
avlNode *temp = minNode(node->right);
|
||||||
node->key = temp->key; /*Copy that to the root*/
|
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.*/
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*single node in tree*/
|
/*single node in tree*/
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return node;
|
return node;
|
||||||
|
|
||||||
|
/*Update height*/
|
||||||
|
node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1);
|
||||||
|
|
||||||
/*Update height*/
|
int balance = heightDiff(node);
|
||||||
node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1);
|
|
||||||
|
|
||||||
int balance = heightDiff(node);
|
/*Left Left */
|
||||||
|
if ((balance > 1) && (heightDiff(node->left) >= 0))
|
||||||
|
return rightRotate(node);
|
||||||
|
|
||||||
/*Left Left */
|
/*Left Right */
|
||||||
if((balance>1) && (heightDiff(node->left) >= 0))
|
if ((balance > 1) && (heightDiff(node->left) < 0))
|
||||||
return rightRotate(node);
|
{
|
||||||
|
node = LeftRightRotate(node);
|
||||||
|
}
|
||||||
|
|
||||||
/*Left Right */
|
/*Right Right */
|
||||||
if ((balance>1) && (heightDiff(node->left) < 0))
|
if ((balance < -1) && (heightDiff(node->right) >= 0))
|
||||||
{
|
return leftRotate(node);
|
||||||
node = LeftRightRotate(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*Right Right */
|
/*Right Left */
|
||||||
if((balance<-1) && (heightDiff(node->right) >= 0))
|
if ((balance < -1) && (heightDiff(node->right) < 0))
|
||||||
return leftRotate(node);
|
{
|
||||||
|
node = RightLeftRotate(node);
|
||||||
/*Right Left */
|
}
|
||||||
if ((balance<-1) && (heightDiff(node->right) < 0))
|
|
||||||
{
|
|
||||||
node = RightLeftRotate(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
return node;
|
|
||||||
|
|
||||||
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
avlNode *findNode(avlNode *node, int queryNum)
|
avlNode *findNode(avlNode *node, int queryNum)
|
||||||
{
|
{
|
||||||
if(node!=NULL)
|
if (node != NULL)
|
||||||
{
|
{
|
||||||
if(queryNum < node->key)
|
if (queryNum < node->key)
|
||||||
node = findNode(node->left, queryNum);
|
node = findNode(node->left, queryNum);
|
||||||
else if(queryNum > node->key)
|
else if (queryNum > node->key)
|
||||||
node = findNode(node->right, queryNum);
|
node = findNode(node->right, queryNum);
|
||||||
}
|
}
|
||||||
|
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printPreOrder(avlNode *node)
|
void printPreOrder(avlNode *node)
|
||||||
{
|
{
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
printf(" %d ", (node->key));
|
printf(" %d ", (node->key));
|
||||||
printPreOrder(node->left);
|
printPreOrder(node->left);
|
||||||
printPreOrder(node->right);
|
printPreOrder(node->right);
|
||||||
}
|
}
|
||||||
|
|
||||||
void printInOrder(avlNode *node)
|
void printInOrder(avlNode *node)
|
||||||
{
|
{
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return;
|
return;
|
||||||
printInOrder(node->left);
|
printInOrder(node->left);
|
||||||
printf(" %d ", (node->key));
|
printf(" %d ", (node->key));
|
||||||
printInOrder(node->right);
|
printInOrder(node->right);
|
||||||
}
|
}
|
||||||
|
|
||||||
void printPostOrder(avlNode *node)
|
void printPostOrder(avlNode *node)
|
||||||
{
|
{
|
||||||
if(node == NULL)
|
if (node == NULL)
|
||||||
return;
|
return;
|
||||||
printPostOrder(node->left);
|
printPostOrder(node->left);
|
||||||
printPostOrder(node->right);
|
printPostOrder(node->right);
|
||||||
printf(" %d ", (node->key));
|
printf(" %d ", (node->key));
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int choice;
|
int choice;
|
||||||
int flag=1;
|
int flag = 1;
|
||||||
int insertNum;
|
int insertNum;
|
||||||
int queryNum;
|
int queryNum;
|
||||||
|
|
||||||
avlNode *root = NULL;
|
avlNode *root = NULL;
|
||||||
avlNode *tempNode;
|
avlNode *tempNode;
|
||||||
|
|
||||||
while(flag == 1)
|
while (flag == 1)
|
||||||
{
|
{
|
||||||
printf("\n\nEnter the Step to Run : \n");
|
printf("\n\nEnter the Step to Run : \n");
|
||||||
|
|
||||||
printf("\t1: Insert a node into AVL tree\n");
|
printf("\t1: Insert a node into AVL tree\n");
|
||||||
printf("\t2: Delete a node in AVL tree\n");
|
printf("\t2: Delete a node in AVL tree\n");
|
||||||
printf("\t3: Search a node into AVL tree\n");
|
printf("\t3: Search a node into AVL tree\n");
|
||||||
printf("\t4: printPreOrder (Ro L R) Tree\n");
|
printf("\t4: printPreOrder (Ro L R) Tree\n");
|
||||||
printf("\t5: printInOrder (L Ro R) Tree\n");
|
printf("\t5: printInOrder (L Ro R) Tree\n");
|
||||||
printf("\t6: printPostOrder (L R Ro) Tree\n");
|
printf("\t6: printPostOrder (L R Ro) Tree\n");
|
||||||
printf("\t7: printAVL Tree\n");
|
printf("\t7: printAVL Tree\n");
|
||||||
|
|
||||||
printf("\t0: EXIT\n");
|
printf("\t0: EXIT\n");
|
||||||
scanf("%d", &choice);
|
scanf("%d", &choice);
|
||||||
|
|
||||||
switch(choice)
|
switch (choice)
|
||||||
{
|
{
|
||||||
case 0:
|
case 0:
|
||||||
{
|
{
|
||||||
flag=0;
|
flag = 0;
|
||||||
printf("\n\t\tExiting, Thank You !!\n");
|
printf("\n\t\tExiting, Thank You !!\n");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 1:
|
case 1:
|
||||||
{
|
{
|
||||||
|
|
||||||
printf("\n\tEnter the Number to insert: ");
|
printf("\n\tEnter the Number to insert: ");
|
||||||
scanf("%d", &insertNum);
|
scanf("%d", &insertNum);
|
||||||
|
|
||||||
tempNode = findNode(root, insertNum);
|
tempNode = findNode(root, insertNum);
|
||||||
|
|
||||||
if(tempNode!=NULL)
|
if (tempNode != NULL)
|
||||||
printf("\n\t %d Already exists in the tree\n", insertNum);
|
printf("\n\t %d Already exists in the tree\n", insertNum);
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
printf("\n\tPrinting AVL Tree\n");
|
printf("\n\tPrinting AVL Tree\n");
|
||||||
printAVL(root, 1);
|
printAVL(root, 1);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
|
|
||||||
root = insert(root, insertNum);
|
root = insert(root, insertNum);
|
||||||
printf("\n\tPrinting AVL Tree\n");
|
printf("\n\tPrinting AVL Tree\n");
|
||||||
printAVL(root, 1);
|
printAVL(root, 1);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 2:
|
case 2:
|
||||||
{
|
{
|
||||||
printf("\n\tEnter the Number to Delete: ");
|
printf("\n\tEnter the Number to Delete: ");
|
||||||
scanf("%d", &queryNum);
|
scanf("%d", &queryNum);
|
||||||
|
|
||||||
tempNode = findNode(root, queryNum);
|
tempNode = findNode(root, queryNum);
|
||||||
|
|
||||||
if(tempNode==NULL)
|
if (tempNode == NULL)
|
||||||
printf("\n\t %d Does not exist in the tree\n", queryNum);
|
printf("\n\t %d Does not exist in the tree\n", queryNum);
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
printf("\n\tPrinting AVL Tree\n");
|
printf("\n\tPrinting AVL Tree\n");
|
||||||
printAVL(root, 1);
|
printAVL(root, 1);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
root = delete(root, queryNum);
|
root = delete (root, queryNum);
|
||||||
|
|
||||||
printf("\n\tPrinting AVL Tree\n");
|
printf("\n\tPrinting AVL Tree\n");
|
||||||
printAVL(root, 1);
|
printAVL(root, 1);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 3:
|
case 3:
|
||||||
{
|
{
|
||||||
printf("\n\tEnter the Number to Search: ");
|
printf("\n\tEnter the Number to Search: ");
|
||||||
scanf("%d", &queryNum);
|
scanf("%d", &queryNum);
|
||||||
|
|
||||||
tempNode = findNode(root, queryNum);
|
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);
|
||||||
|
|
||||||
if(tempNode == NULL)
|
printf("\n\tPrinting AVL Tree\n");
|
||||||
printf("\n\t %d : Not Found\n", queryNum);
|
printAVL(root, 1);
|
||||||
else
|
printf("\n");
|
||||||
{
|
}
|
||||||
printf("\n\t %d : Found at height %d \n", queryNum, tempNode->height);
|
|
||||||
|
|
||||||
printf("\n\tPrinting AVL Tree\n");
|
break;
|
||||||
printAVL(root, 1);
|
}
|
||||||
printf("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
case 4:
|
||||||
}
|
{
|
||||||
|
printf("\nPrinting Tree preOrder\n");
|
||||||
|
printPreOrder(root);
|
||||||
|
|
||||||
case 4:
|
break;
|
||||||
{
|
}
|
||||||
printf("\nPrinting Tree preOrder\n");
|
|
||||||
printPreOrder(root);
|
|
||||||
|
|
||||||
break;
|
case 5:
|
||||||
}
|
{
|
||||||
|
printf("\nPrinting Tree inOrder\n");
|
||||||
|
printInOrder(root);
|
||||||
|
|
||||||
case 5:
|
break;
|
||||||
{
|
}
|
||||||
printf("\nPrinting Tree inOrder\n");
|
|
||||||
printInOrder(root);
|
|
||||||
|
|
||||||
break;
|
case 6:
|
||||||
}
|
{
|
||||||
|
printf("\nPrinting Tree PostOrder\n");
|
||||||
|
printPostOrder(root);
|
||||||
|
|
||||||
case 6:
|
break;
|
||||||
{
|
}
|
||||||
printf("\nPrinting Tree PostOrder\n");
|
|
||||||
printPostOrder(root);
|
|
||||||
|
|
||||||
break;
|
case 7:
|
||||||
}
|
{
|
||||||
|
printf("\nPrinting AVL Tree\n");
|
||||||
|
printAVL(root, 1);
|
||||||
|
|
||||||
case 7:
|
break;
|
||||||
{
|
}
|
||||||
printf("\nPrinting AVL Tree\n");
|
|
||||||
printAVL(root, 1);
|
|
||||||
|
|
||||||
break;
|
default:
|
||||||
}
|
{
|
||||||
|
flag = 0;
|
||||||
|
printf("\n\t\tExiting, Thank You !!\n");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
default:
|
return 0;
|
||||||
{
|
|
||||||
flag=0;
|
|
||||||
printf("\n\t\tExiting, Thank You !!\n");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.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
|
- Insertion
|
||||||
- Deletion
|
- Deletion
|
||||||
- Search by key value
|
- Search by key value
|
||||||
@ -9,198 +10,237 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Node, the basic data structure in the tree
|
// Node, the basic data structure in the tree
|
||||||
typedef struct node{
|
typedef struct node
|
||||||
|
{
|
||||||
|
|
||||||
// left child
|
// left child
|
||||||
struct node* left;
|
struct node *left;
|
||||||
|
|
||||||
// right child
|
// right child
|
||||||
struct node* right;
|
struct node *right;
|
||||||
|
|
||||||
// data of the node
|
// data of the node
|
||||||
int data;
|
int data;
|
||||||
} node;
|
} node;
|
||||||
|
|
||||||
// The node constructor, which receives the key value input and returns a node pointer
|
// The node constructor, which receives the key value input and returns a node
|
||||||
node* newNode(int data){
|
// pointer
|
||||||
|
node *newNode(int data)
|
||||||
|
{
|
||||||
|
|
||||||
// creates a slug
|
// creates a slug
|
||||||
node* tmp = (node*)malloc(sizeof(node));
|
node *tmp = (node *)malloc(sizeof(node));
|
||||||
|
|
||||||
// initializes the slug
|
// initializes the slug
|
||||||
tmp->data = data;
|
tmp->data = data;
|
||||||
tmp->left = NULL;
|
tmp->left = NULL;
|
||||||
tmp->right = NULL;
|
tmp->right = NULL;
|
||||||
|
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Insertion procedure, which inserts the input key in a new node in the tree
|
// 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)
|
// If the root of the subtree is null, insert key here
|
||||||
root = newNode(data);
|
if (root == NULL)
|
||||||
// If it isn't null and the input key is greater than the root key, insert in the right leaf
|
root = newNode(data);
|
||||||
else if (data > root->data)
|
// If it isn't null and the input key is greater than the root key, insert
|
||||||
root->right = insert(root->right, data);
|
// in the right 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)
|
||||||
else if (data < root->data)
|
root->right = insert(root->right, data);
|
||||||
root->left = insert(root->left, data);
|
// If it isn't null and the input key is lower than the root key, insert in
|
||||||
// Returns the modified tree
|
// the left leaf
|
||||||
return root;
|
else if (data < root->data)
|
||||||
|
root->left = insert(root->left, data);
|
||||||
|
// Returns the modified tree
|
||||||
|
return root;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Utilitary procedure to find the greatest key in the left subtree
|
// 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)
|
// If there's no leaf to the right, then this is the maximum key value
|
||||||
return root;
|
if (root->right == NULL)
|
||||||
else
|
return root;
|
||||||
root->right = getMax(root->right);
|
else
|
||||||
|
root->right = getMax(root->right);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deletion procedure, which searches for the input key in the tree and removes it if present
|
// Deletion procedure, which searches for the input key in the tree and removes
|
||||||
node* delete(node* root, int data){
|
// it if present
|
||||||
// If the root is null, nothing to be done
|
node *delete (node *root, int data)
|
||||||
if (root == NULL)
|
{
|
||||||
return root;
|
// If the root is null, nothing to be done
|
||||||
// If the input key is greater than the root's, search in the right subtree
|
if (root == NULL)
|
||||||
else if (data > root->data)
|
return root;
|
||||||
root->right = delete(root->right, data);
|
// If the input key is greater than the root's, search in the right subtree
|
||||||
// If the input key is lower than the root's, search in the left subtree
|
else if (data > root->data)
|
||||||
else if (data < root->data)
|
root->right = delete (root->right, data);
|
||||||
root->left = delete(root->left, data);
|
// If the input key is lower than the root's, search in the left subtree
|
||||||
// If the input key matches the root's, check the following cases
|
else if (data < root->data)
|
||||||
// termination condition
|
root->left = delete (root->left, data);
|
||||||
else if (data == root->data){
|
// If the input key matches the root's, check the following cases
|
||||||
// Case 1: the root has no leaves, remove the node
|
// termination condition
|
||||||
if ((root->left == NULL) && (root->right == NULL)){
|
else if (data == root->data)
|
||||||
free(root);
|
{
|
||||||
return NULL;
|
// Case 1: the root has no leaves, remove the node
|
||||||
}
|
if ((root->left == NULL) && (root->right == NULL))
|
||||||
// Case 2: the root has one leaf, make the leaf the new root and remove the old root
|
{
|
||||||
else if (root->left == NULL){
|
free(root);
|
||||||
node* tmp = root;
|
return NULL;
|
||||||
root = root->right;
|
}
|
||||||
free(tmp);
|
// Case 2: the root has one leaf, make the leaf the new root and remove
|
||||||
return root;
|
// the old root
|
||||||
}
|
else if (root->left == NULL)
|
||||||
else if (root->right == NULL){
|
{
|
||||||
node* tmp = root;
|
node *tmp = root;
|
||||||
root = root->left;
|
root = root->right;
|
||||||
free(tmp);
|
free(tmp);
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
// Case 3: the root has 2 leaves, find the greatest key in the left subtree and switch with the root's
|
else if (root->right == NULL)
|
||||||
else {
|
{
|
||||||
|
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
|
||||||
|
{
|
||||||
|
|
||||||
// finds the biggest node in the left branch.
|
// finds the biggest node in the left branch.
|
||||||
node* tmp = getMax(root->left);
|
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
|
||||||
root->data = tmp->data;
|
// (lefts)
|
||||||
root->left = delete(root->left, tmp->data);
|
root->data = tmp->data;
|
||||||
}
|
root->left = delete (root->left, tmp->data);
|
||||||
}
|
}
|
||||||
return root;
|
}
|
||||||
|
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
|
// Search procedure, which looks for the input key in the tree and returns 1 if
|
||||||
int find(node* root, int data){
|
// it's present or 0 if it's not in the tree
|
||||||
// If the root is null, the key's not present
|
int find(node *root, int data)
|
||||||
if (root == NULL)
|
{
|
||||||
return 0;
|
// If the root is null, the key's not present
|
||||||
// If the input key is greater than the root's, search in the right subtree
|
if (root == NULL)
|
||||||
else if (data > root->data)
|
return 0;
|
||||||
return find(root->right, data);
|
// If the input key is greater than the root's, search in the right subtree
|
||||||
// If the input key is lower than the root's, search in the left subtree
|
else if (data > root->data)
|
||||||
else if (data < root->data)
|
return find(root->right, data);
|
||||||
return find(root->left, data);
|
// If the input key is lower than the root's, search in the left subtree
|
||||||
// If the input and the root key match, return 1
|
else if (data < root->data)
|
||||||
else if (data == root->data)
|
return find(root->left, data);
|
||||||
return 1;
|
// If the input and the root key match, return 1
|
||||||
|
else if (data == root->data)
|
||||||
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Utilitary procedure to measure the height of the binary tree
|
// 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)
|
// If the root is null, this is the bottom of the tree (height 0)
|
||||||
return 0;
|
if (root == NULL)
|
||||||
else{
|
return 0;
|
||||||
// Get the height from both left and right subtrees to check which is the greatest
|
else
|
||||||
int right_h = height(root->right);
|
{
|
||||||
int left_h = height(root->left);
|
// 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)
|
||||||
if (right_h > left_h)
|
// plus 1(which is the root's level)
|
||||||
return (right_h + 1);
|
if (right_h > left_h)
|
||||||
else
|
return (right_h + 1);
|
||||||
return (left_h + 1);
|
else
|
||||||
}
|
return (left_h + 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Utilitary procedure to free all nodes in a tree
|
// Utilitary procedure to free all nodes in a tree
|
||||||
void purge(node* root){
|
void purge(node *root)
|
||||||
if (root != NULL){
|
{
|
||||||
if (root->left != NULL)
|
if (root != NULL)
|
||||||
purge(root->left);
|
{
|
||||||
if (root->right != NULL)
|
if (root->left != NULL)
|
||||||
purge(root->right);
|
purge(root->left);
|
||||||
free(root);
|
if (root->right != NULL)
|
||||||
}
|
purge(root->right);
|
||||||
|
free(root);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Traversal procedure to list the current keys in the tree in order of value (from the left to the right)
|
// Traversal procedure to list the current keys in the tree in order of value
|
||||||
void inOrder(node* root){
|
// (from the left to the right)
|
||||||
if(root != NULL){
|
void inOrder(node *root)
|
||||||
inOrder(root->left);
|
{
|
||||||
printf("\t[ %d ]\t", root->data);
|
if (root != NULL)
|
||||||
inOrder(root->right);
|
{
|
||||||
}
|
inOrder(root->left);
|
||||||
|
printf("\t[ %d ]\t", root->data);
|
||||||
|
inOrder(root->right);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void main(){
|
void main()
|
||||||
|
{
|
||||||
|
|
||||||
// this reference don't change.
|
// this reference don't change.
|
||||||
// only the tree changes.
|
// only the tree changes.
|
||||||
node* root = NULL;
|
node *root = NULL;
|
||||||
int opt = -1;
|
int opt = -1;
|
||||||
int data = 0;
|
int data = 0;
|
||||||
|
|
||||||
// event-loop.
|
// event-loop.
|
||||||
while (opt != 0){
|
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
|
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
|
// processes the choice
|
||||||
switch(opt){
|
switch (opt)
|
||||||
case 1: printf("Enter the new node's value:\n");
|
{
|
||||||
scanf("%d",&data);
|
case 1:
|
||||||
root = insert(root,data);
|
printf("Enter the new node's value:\n");
|
||||||
break;
|
scanf("%d", &data);
|
||||||
|
root = insert(root, data);
|
||||||
|
break;
|
||||||
|
|
||||||
case 2: printf("Enter the value to be removed:\n");
|
case 2:
|
||||||
if (root != NULL){
|
printf("Enter the value to be removed:\n");
|
||||||
scanf("%d",&data);
|
if (root != NULL)
|
||||||
root = delete(root,data);
|
{
|
||||||
}
|
scanf("%d", &data);
|
||||||
else
|
root = delete (root, data);
|
||||||
printf("Tree is already empty!\n");
|
}
|
||||||
break;
|
else
|
||||||
|
printf("Tree is already empty!\n");
|
||||||
|
break;
|
||||||
|
|
||||||
case 3: printf("Enter the searched value:\n");
|
case 3:
|
||||||
scanf("%d",&data);
|
printf("Enter the searched value:\n");
|
||||||
find(root,data) ? printf("The value is in the tree.\n") : printf("The value is not in the tree.\n");
|
scanf("%d", &data);
|
||||||
break;
|
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:
|
||||||
break;
|
printf("Current height of the tree is: %d\n", height(root));
|
||||||
|
break;
|
||||||
|
|
||||||
case 5: inOrder(root);
|
case 5:
|
||||||
break;
|
inOrder(root);
|
||||||
}
|
break;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// deletes the tree from the heap.
|
// deletes the tree from the heap.
|
||||||
purge(root);
|
purge(root);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/* Includes structure for a node and a newNode() function which
|
/* Includes structure for a node and a newNode() function which
|
||||||
can be used to create a new node in the tree.
|
can be used to create a new node in the tree.
|
||||||
It is assumed that the data in nodes will be an integer, though
|
It is assumed that the data in nodes will be an integer, though
|
||||||
function can be modified according to the data type, easily.
|
function can be modified according to the data type, easily.
|
||||||
*/
|
*/
|
||||||
@ -35,5 +35,5 @@ int main(void)
|
|||||||
nameOfNode->leftNode and so on.
|
nameOfNode->leftNode and so on.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
void inOrderTraversal(struct node *node)
|
void inOrderTraversal(struct node *node)
|
||||||
{
|
{
|
||||||
if(node == NULL) //if tree is empty
|
if (node == NULL) // if tree is empty
|
||||||
return;
|
return;
|
||||||
|
|
||||||
inOrderTraversal(node->leftNode);
|
inOrderTraversal(node->leftNode);
|
||||||
@ -17,7 +17,7 @@ void inOrderTraversal(struct node *node)
|
|||||||
|
|
||||||
void preOrderTraversal(struct node *node)
|
void preOrderTraversal(struct node *node)
|
||||||
{
|
{
|
||||||
if(node == NULL) //if tree is empty
|
if (node == NULL) // if tree is empty
|
||||||
return;
|
return;
|
||||||
|
|
||||||
printf("\t%d\t", node->data);
|
printf("\t%d\t", node->data);
|
||||||
@ -27,12 +27,12 @@ void preOrderTraversal(struct node *node)
|
|||||||
|
|
||||||
void postOrderTraversal(struct node *node)
|
void postOrderTraversal(struct node *node)
|
||||||
{
|
{
|
||||||
if(node == NULL) //if tree is empty
|
if (node == NULL) // if tree is empty
|
||||||
return;
|
return;
|
||||||
|
|
||||||
postOrderTraversal(node->leftNode);
|
postOrderTraversal(node->leftNode);
|
||||||
postOrderTraversal(node->rightNode);
|
postOrderTraversal(node->rightNode);
|
||||||
printf("\t%d\t",node->data);
|
printf("\t%d\t", node->data);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
@ -41,5 +41,5 @@ int main(void)
|
|||||||
function with a pointer to the root node.
|
function with a pointer to the root node.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
@ -1,18 +1,20 @@
|
|||||||
|
#include <math.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <math.h>
|
|
||||||
|
|
||||||
typedef struct node{
|
typedef struct node
|
||||||
|
{
|
||||||
int val;
|
int val;
|
||||||
struct node* par;
|
struct node *par;
|
||||||
struct node* left;
|
struct node *left;
|
||||||
struct node* right;
|
struct node *right;
|
||||||
int color;
|
int color;
|
||||||
}Node;
|
} Node;
|
||||||
|
|
||||||
// Create a new node
|
// Create a new node
|
||||||
Node* newNode(int val, Node* par){
|
Node *newNode(int val, Node *par)
|
||||||
Node* create = (Node*)(malloc(sizeof(Node)));
|
{
|
||||||
|
Node *create = (Node *)(malloc(sizeof(Node)));
|
||||||
create->val = val;
|
create->val = val;
|
||||||
create->par = par;
|
create->par = par;
|
||||||
create->left = NULL;
|
create->left = NULL;
|
||||||
@ -21,30 +23,37 @@ Node* newNode(int val, Node* par){
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if the node is the leaf
|
// Check if the node is the leaf
|
||||||
int isLeaf(Node* n){
|
int isLeaf(Node *n)
|
||||||
if(n->left == NULL && n->right == NULL){
|
{
|
||||||
|
if (n->left == NULL && n->right == NULL)
|
||||||
|
{
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Left Rotate
|
// Left Rotate
|
||||||
Node* leftRotate(Node* node){
|
Node *leftRotate(Node *node)
|
||||||
Node* parent = node->par;
|
{
|
||||||
Node* grandParent = parent->par;
|
Node *parent = node->par;
|
||||||
|
Node *grandParent = parent->par;
|
||||||
|
|
||||||
parent->right = node->left;
|
parent->right = node->left;
|
||||||
if(node->left != NULL){
|
if (node->left != NULL)
|
||||||
|
{
|
||||||
node->left->par = parent;
|
node->left->par = parent;
|
||||||
}
|
}
|
||||||
node->par = grandParent;
|
node->par = grandParent;
|
||||||
parent->par = node;
|
parent->par = node;
|
||||||
node->left = parent;
|
node->left = parent;
|
||||||
if(grandParent != NULL){
|
if (grandParent != NULL)
|
||||||
if(grandParent->right == parent){
|
{
|
||||||
|
if (grandParent->right == parent)
|
||||||
|
{
|
||||||
grandParent->right = node;
|
grandParent->right = node;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
grandParent->left = node;
|
grandParent->left = node;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -52,73 +61,86 @@ Node* leftRotate(Node* node){
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Right Rotate
|
// Right Rotate
|
||||||
Node* rightRotate(Node* node){
|
Node *rightRotate(Node *node)
|
||||||
Node* parent = node->par;
|
{
|
||||||
Node* grandParent = parent->par;
|
Node *parent = node->par;
|
||||||
|
Node *grandParent = parent->par;
|
||||||
|
|
||||||
parent->left = node->right;
|
parent->left = node->right;
|
||||||
if(node->right != NULL){
|
if (node->right != NULL)
|
||||||
|
{
|
||||||
node->right->par = parent;
|
node->right->par = parent;
|
||||||
}
|
}
|
||||||
node->par = grandParent;
|
node->par = grandParent;
|
||||||
parent->par = node;
|
parent->par = node;
|
||||||
node->right = parent;
|
node->right = parent;
|
||||||
if(grandParent != NULL){
|
if (grandParent != NULL)
|
||||||
if(grandParent->right == parent){
|
{
|
||||||
|
if (grandParent->right == parent)
|
||||||
|
{
|
||||||
grandParent->right = node;
|
grandParent->right = node;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
grandParent->left = node;
|
grandParent->left = node;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Check the node after the insertion step
|
// Check the node after the insertion step
|
||||||
void checkNode(Node* node){
|
void checkNode(Node *node)
|
||||||
|
{
|
||||||
|
|
||||||
// If the node is the root
|
// If the node is the root
|
||||||
if(node == NULL || node->par == NULL){
|
if (node == NULL || node->par == NULL)
|
||||||
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Node* child = node;
|
Node *child = node;
|
||||||
//If it is a black node or its parent is a black 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
|
// Dont Do Anything
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both parent and child are red
|
// Both parent and child are red
|
||||||
// Check For Uncle
|
// Check For Uncle
|
||||||
Node* parent = node->par;
|
Node *parent = node->par;
|
||||||
Node* grandParent = parent->par;
|
Node *grandParent = parent->par;
|
||||||
|
|
||||||
// If grandParent is NULL, then parent is the root.
|
// If grandParent is NULL, then parent is the root.
|
||||||
// Just make the root black.
|
// Just make the root black.
|
||||||
if(grandParent == NULL){
|
if (grandParent == NULL)
|
||||||
|
{
|
||||||
parent->color = 0;
|
parent->color = 0;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// If both the children of the grandParent are red
|
// 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
|
// Make the grandParent red and both of its children black
|
||||||
(grandParent->right)->color = 0;
|
(grandParent->right)->color = 0;
|
||||||
(grandParent->left)->color = 0;
|
(grandParent->left)->color = 0;
|
||||||
grandParent->color = 1;
|
grandParent->color = 1;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
// The only option left is rotation.
|
// The only option left is rotation.
|
||||||
Node* greatGrandParent = grandParent->par;
|
Node *greatGrandParent = grandParent->par;
|
||||||
// Right Case
|
// Right Case
|
||||||
if(grandParent->right == parent){
|
if (grandParent->right == parent)
|
||||||
//Right Right Case
|
{
|
||||||
if(parent->right == node){
|
// Right Right Case
|
||||||
|
if (parent->right == node)
|
||||||
|
{
|
||||||
grandParent->right = parent->left;
|
grandParent->right = parent->left;
|
||||||
if(parent->left != NULL){
|
if (parent->left != NULL)
|
||||||
|
{
|
||||||
(parent->left)->par = grandParent;
|
(parent->left)->par = grandParent;
|
||||||
}
|
}
|
||||||
parent->left = grandParent;
|
parent->left = grandParent;
|
||||||
@ -126,11 +148,15 @@ void checkNode(Node* node){
|
|||||||
|
|
||||||
// Attach to existing Tree;
|
// Attach to existing Tree;
|
||||||
parent->par = greatGrandParent;
|
parent->par = greatGrandParent;
|
||||||
if(greatGrandParent != NULL){
|
if (greatGrandParent != NULL)
|
||||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
{
|
||||||
|
if (greatGrandParent->left != NULL &&
|
||||||
|
greatGrandParent->left == grandParent)
|
||||||
|
{
|
||||||
greatGrandParent->left = parent;
|
greatGrandParent->left = parent;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
greatGrandParent->right = parent;
|
greatGrandParent->right = parent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -139,18 +165,21 @@ void checkNode(Node* node){
|
|||||||
parent->color = 0;
|
parent->color = 0;
|
||||||
grandParent->color = 1;
|
grandParent->color = 1;
|
||||||
}
|
}
|
||||||
else{ // Right Left Case
|
else
|
||||||
|
{ // Right Left Case
|
||||||
// First step -> Parent Child Rotation
|
// First step -> Parent Child Rotation
|
||||||
parent->left = child->right;
|
parent->left = child->right;
|
||||||
if(child->right != NULL){
|
if (child->right != NULL)
|
||||||
|
{
|
||||||
(child->right)->par = parent;
|
(child->right)->par = parent;
|
||||||
}
|
}
|
||||||
child->right = parent;
|
child->right = parent;
|
||||||
parent->par = child;
|
parent->par = child;
|
||||||
|
|
||||||
// Second step -> Child and GrandParent Rotation
|
// Second step -> Child and GrandParent Rotation
|
||||||
grandParent->right = child->left;
|
grandParent->right = child->left;
|
||||||
if(child->left != NULL){
|
if (child->left != NULL)
|
||||||
|
{
|
||||||
(child->left)->par = grandParent;
|
(child->left)->par = grandParent;
|
||||||
}
|
}
|
||||||
child->left = grandParent;
|
child->left = grandParent;
|
||||||
@ -158,11 +187,15 @@ void checkNode(Node* node){
|
|||||||
|
|
||||||
// Attach to the existing tree
|
// Attach to the existing tree
|
||||||
child->par = greatGrandParent;
|
child->par = greatGrandParent;
|
||||||
if(greatGrandParent != NULL){
|
if (greatGrandParent != NULL)
|
||||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
{
|
||||||
|
if (greatGrandParent->left != NULL &&
|
||||||
|
greatGrandParent->left == grandParent)
|
||||||
|
{
|
||||||
greatGrandParent->left = child;
|
greatGrandParent->left = child;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
greatGrandParent->right = child;
|
greatGrandParent->right = child;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -172,11 +205,14 @@ void checkNode(Node* node){
|
|||||||
grandParent->color = 1;
|
grandParent->color = 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{ // Left Case
|
else
|
||||||
//Left Left Case
|
{ // Left Case
|
||||||
if(parent->left == node){
|
// Left Left Case
|
||||||
|
if (parent->left == node)
|
||||||
|
{
|
||||||
grandParent->left = parent->right;
|
grandParent->left = parent->right;
|
||||||
if(parent->right != NULL){
|
if (parent->right != NULL)
|
||||||
|
{
|
||||||
(parent->right)->par = grandParent;
|
(parent->right)->par = grandParent;
|
||||||
}
|
}
|
||||||
parent->right = grandParent;
|
parent->right = grandParent;
|
||||||
@ -184,11 +220,15 @@ void checkNode(Node* node){
|
|||||||
|
|
||||||
// Attach to existing Tree;
|
// Attach to existing Tree;
|
||||||
parent->par = greatGrandParent;
|
parent->par = greatGrandParent;
|
||||||
if(greatGrandParent != NULL){
|
if (greatGrandParent != NULL)
|
||||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
{
|
||||||
|
if (greatGrandParent->left != NULL &&
|
||||||
|
greatGrandParent->left == grandParent)
|
||||||
|
{
|
||||||
greatGrandParent->left = parent;
|
greatGrandParent->left = parent;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
greatGrandParent->right = parent;
|
greatGrandParent->right = parent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -197,19 +237,22 @@ void checkNode(Node* node){
|
|||||||
parent->color = 0;
|
parent->color = 0;
|
||||||
grandParent->color = 1;
|
grandParent->color = 1;
|
||||||
}
|
}
|
||||||
else{ //Left Right Case
|
else
|
||||||
|
{ // Left Right Case
|
||||||
|
|
||||||
// First step -> Parent Child Rotation
|
// First step -> Parent Child Rotation
|
||||||
parent->right = child->left;
|
parent->right = child->left;
|
||||||
if(child->left != NULL){
|
if (child->left != NULL)
|
||||||
|
{
|
||||||
(child->left)->par = parent;
|
(child->left)->par = parent;
|
||||||
}
|
}
|
||||||
child->left = parent;
|
child->left = parent;
|
||||||
parent->par = child;
|
parent->par = child;
|
||||||
|
|
||||||
// Second step -> Child and GrandParent Rotation
|
// Second step -> Child and GrandParent Rotation
|
||||||
grandParent->left = child->right;
|
grandParent->left = child->right;
|
||||||
if(child->right != NULL){
|
if (child->right != NULL)
|
||||||
|
{
|
||||||
(child->right)->par = grandParent;
|
(child->right)->par = grandParent;
|
||||||
}
|
}
|
||||||
child->right = grandParent;
|
child->right = grandParent;
|
||||||
@ -217,11 +260,15 @@ void checkNode(Node* node){
|
|||||||
|
|
||||||
// Attach to the existing tree
|
// Attach to the existing tree
|
||||||
child->par = greatGrandParent;
|
child->par = greatGrandParent;
|
||||||
if(greatGrandParent != NULL){
|
if (greatGrandParent != NULL)
|
||||||
if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){
|
{
|
||||||
|
if (greatGrandParent->left != NULL &&
|
||||||
|
greatGrandParent->left == grandParent)
|
||||||
|
{
|
||||||
greatGrandParent->left = child;
|
greatGrandParent->left = child;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
greatGrandParent->right = child;
|
greatGrandParent->right = child;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -235,71 +282,88 @@ void checkNode(Node* node){
|
|||||||
}
|
}
|
||||||
|
|
||||||
// To insert a node in the existing tree
|
// 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){
|
Node *buffRoot = *root;
|
||||||
if(buffRoot->val > val){
|
while (buffRoot)
|
||||||
|
{
|
||||||
|
if (buffRoot->val > val)
|
||||||
|
{
|
||||||
// Go left
|
// Go left
|
||||||
if(buffRoot->left != NULL){
|
if (buffRoot->left != NULL)
|
||||||
|
{
|
||||||
buffRoot = buffRoot->left;
|
buffRoot = buffRoot->left;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
//Insert The Node
|
{
|
||||||
Node* toInsert = newNode(val, buffRoot);
|
// Insert The Node
|
||||||
|
Node *toInsert = newNode(val, buffRoot);
|
||||||
buffRoot->left = toInsert;
|
buffRoot->left = toInsert;
|
||||||
buffRoot = toInsert;
|
buffRoot = toInsert;
|
||||||
|
|
||||||
//Check For Double Red Problems
|
// Check For Double Red Problems
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
|
|
||||||
// Go right
|
// Go right
|
||||||
if(buffRoot->right != NULL){
|
if (buffRoot->right != NULL)
|
||||||
|
{
|
||||||
buffRoot = buffRoot->right;
|
buffRoot = buffRoot->right;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
//Insert The Node
|
{
|
||||||
Node* toInsert = newNode(val, buffRoot);
|
// Insert The Node
|
||||||
|
Node *toInsert = newNode(val, buffRoot);
|
||||||
buffRoot->right = toInsert;
|
buffRoot->right = toInsert;
|
||||||
buffRoot = toInsert;
|
buffRoot = toInsert;
|
||||||
|
|
||||||
//Check For Double Red Problems
|
// Check For Double Red Problems
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
while (buffRoot != *root)
|
||||||
while(buffRoot != *root){
|
{
|
||||||
checkNode(buffRoot);
|
checkNode(buffRoot);
|
||||||
if(buffRoot->par == NULL){
|
if (buffRoot->par == NULL)
|
||||||
|
{
|
||||||
*root = buffRoot;
|
*root = buffRoot;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
buffRoot = buffRoot->par;
|
buffRoot = buffRoot->par;
|
||||||
if(buffRoot == *root){
|
if (buffRoot == *root)
|
||||||
|
{
|
||||||
buffRoot->color = 0;
|
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;
|
(*root)->color = 0;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!delete && toDelete->color == 1){
|
if (!delete &&toDelete->color == 1)
|
||||||
if(!fromDirection){
|
{
|
||||||
if(toDelete->right != NULL){
|
if (!fromDirection)
|
||||||
|
{
|
||||||
|
if (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete->right->color = 1;
|
toDelete->right->color = 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
if(toDelete->left != NULL){
|
{
|
||||||
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete->left->color = 1;
|
toDelete->left->color = 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -307,26 +371,31 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Get the sibling for further inspection
|
// Get the sibling for further inspection
|
||||||
Node* sibling;
|
Node *sibling;
|
||||||
Node* parent = toDelete->par;
|
Node *parent = toDelete->par;
|
||||||
int locateChild = 0; // 0 if toDeleted is left of its parent else 1
|
int locateChild = 0; // 0 if toDeleted is left of its parent else 1
|
||||||
if(parent->right == toDelete){
|
if (parent->right == toDelete)
|
||||||
|
{
|
||||||
sibling = parent->left;
|
sibling = parent->left;
|
||||||
locateChild = 1;
|
locateChild = 1;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
sibling = parent->right;
|
sibling = parent->right;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Case 2.1. i.e. if the any children of the sibling is red
|
// 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
|
// Sibling is left and child is right. i.e. LEFT RIGHT ROTATION
|
||||||
if(locateChild == 1){
|
if (locateChild == 1)
|
||||||
|
{
|
||||||
|
|
||||||
int parColor = parent->color;
|
int parColor = parent->color;
|
||||||
|
|
||||||
// Step 1: Left rotate sibling
|
// Step 1: Left rotate sibling
|
||||||
@ -336,7 +405,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent = rightRotate(sibling);
|
parent = rightRotate(sibling);
|
||||||
|
|
||||||
// Check if the root is rotated
|
// Check if the root is rotated
|
||||||
if(parent->par == NULL){
|
if (parent->par == NULL)
|
||||||
|
{
|
||||||
*root = parent;
|
*root = parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -346,16 +416,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent->right->color = 0;
|
parent->right->color = 0;
|
||||||
|
|
||||||
// Delete the node (present at parent->right->right)
|
// Delete the node (present at parent->right->right)
|
||||||
if(delete){
|
if (delete)
|
||||||
if(toDelete->left != NULL){
|
{
|
||||||
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete->left->par = parent->right;
|
toDelete->left->par = parent->right;
|
||||||
}
|
}
|
||||||
parent->right->right = toDelete->left;
|
parent->right->right = toDelete->left;
|
||||||
free(toDelete);
|
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;
|
int parColor = parent->color;
|
||||||
|
|
||||||
@ -363,7 +436,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent = leftRotate(sibling);
|
parent = leftRotate(sibling);
|
||||||
|
|
||||||
// Check if the root is rotated
|
// Check if the root is rotated
|
||||||
if(parent->par == NULL){
|
if (parent->par == NULL)
|
||||||
|
{
|
||||||
*root = parent;
|
*root = parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -373,21 +447,24 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent->right->color = 0;
|
parent->right->color = 0;
|
||||||
|
|
||||||
// Delete the node (present at parent->left->left)
|
// Delete the node (present at parent->left->left)
|
||||||
if(delete){
|
if (delete)
|
||||||
if(toDelete->right != NULL){
|
{
|
||||||
|
if (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete->right->par = parent->left;
|
toDelete->right->par = parent->left;
|
||||||
}
|
}
|
||||||
parent->left->left = toDelete->left;
|
parent->left->left = toDelete->left;
|
||||||
free(toDelete);
|
free(toDelete);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
|
|
||||||
// Sibling is right and child is left. i.e. RIGHT LEFT ROTATION
|
// Sibling is right and child is left. i.e. RIGHT LEFT ROTATION
|
||||||
if(locateChild == 0){
|
if (locateChild == 0)
|
||||||
|
{
|
||||||
|
|
||||||
int parColor = parent->color;
|
int parColor = parent->color;
|
||||||
|
|
||||||
// Step 1: Right rotate sibling
|
// Step 1: Right rotate sibling
|
||||||
@ -400,7 +477,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent = leftRotate(sibling);
|
parent = leftRotate(sibling);
|
||||||
|
|
||||||
// Check if the root is rotated
|
// Check if the root is rotated
|
||||||
if(parent->par == NULL){
|
if (parent->par == NULL)
|
||||||
|
{
|
||||||
*root = parent;
|
*root = parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -410,17 +488,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent->right->color = 0;
|
parent->right->color = 0;
|
||||||
|
|
||||||
// Delete the node (present at parent->left->left)
|
// Delete the node (present at parent->left->left)
|
||||||
if(delete){
|
if (delete)
|
||||||
if(toDelete->right != NULL){
|
{
|
||||||
|
if (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete->right->par = parent->left;
|
toDelete->right->par = parent->left;
|
||||||
}
|
}
|
||||||
parent->left->left = toDelete->right;
|
parent->left->left = toDelete->right;
|
||||||
free(toDelete);
|
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;
|
int parColor = parent->color;
|
||||||
|
|
||||||
@ -428,7 +508,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent = rightRotate(sibling);
|
parent = rightRotate(sibling);
|
||||||
|
|
||||||
// Check if the root is rotated
|
// Check if the root is rotated
|
||||||
if(parent->par == NULL){
|
if (parent->par == NULL)
|
||||||
|
{
|
||||||
*root = parent;
|
*root = parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -438,33 +519,40 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent->right->color = 0;
|
parent->right->color = 0;
|
||||||
|
|
||||||
// Delete the node (present at parent->right->right)
|
// Delete the node (present at parent->right->right)
|
||||||
if(delete){
|
if (delete)
|
||||||
if(toDelete->left != NULL){
|
{
|
||||||
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete->left->par = parent->right;
|
toDelete->left->par = parent->right;
|
||||||
}
|
}
|
||||||
parent->right->right = toDelete->left;
|
parent->right->right = toDelete->left;
|
||||||
free(toDelete);
|
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
|
// Recolor the sibling
|
||||||
sibling->color = 1;
|
sibling->color = 1;
|
||||||
|
|
||||||
// Delete if necessary
|
// Delete if necessary
|
||||||
if(delete){
|
if (delete)
|
||||||
if(locateChild){
|
{
|
||||||
|
if (locateChild)
|
||||||
|
{
|
||||||
toDelete->par->right = toDelete->left;
|
toDelete->par->right = toDelete->left;
|
||||||
if(toDelete->left != NULL){
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete->left->par = toDelete->par;
|
toDelete->left->par = toDelete->par;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
toDelete->par->left = toDelete->right;
|
toDelete->par->left = toDelete->right;
|
||||||
if(toDelete->right != NULL){
|
if (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete->right->par = toDelete->par;
|
toDelete->right->par = toDelete->par;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -472,18 +560,22 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
|
|
||||||
checkForCase2(parent, 0, locateChild, root);
|
checkForCase2(parent, 0, locateChild, root);
|
||||||
}
|
}
|
||||||
else{ // Bring the sibling on top and apply 2.1 or 2.2 accordingly
|
else
|
||||||
if(locateChild){ //Right Rotate
|
{ // Bring the sibling on top and apply 2.1 or 2.2 accordingly
|
||||||
|
if (locateChild)
|
||||||
|
{ // Right Rotate
|
||||||
|
|
||||||
toDelete->par->right = toDelete->left;
|
toDelete->par->right = toDelete->left;
|
||||||
if(toDelete->left != NULL){
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete->left->par = toDelete->par;
|
toDelete->left->par = toDelete->par;
|
||||||
}
|
}
|
||||||
|
|
||||||
parent = rightRotate(sibling);
|
parent = rightRotate(sibling);
|
||||||
|
|
||||||
// Check if the root is rotated
|
// Check if the root is rotated
|
||||||
if(parent->par == NULL){
|
if (parent->par == NULL)
|
||||||
|
{
|
||||||
*root = parent;
|
*root = parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -491,16 +583,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
parent->right->color = 1;
|
parent->right->color = 1;
|
||||||
checkForCase2(parent->right, 0, 1, root);
|
checkForCase2(parent->right, 0, 1, root);
|
||||||
}
|
}
|
||||||
else{ // Left Rotate
|
else
|
||||||
|
{ // Left Rotate
|
||||||
|
|
||||||
toDelete->par->left = toDelete->right;
|
toDelete->par->left = toDelete->right;
|
||||||
if(toDelete->right != NULL){
|
if (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete->right->par = toDelete->par;
|
toDelete->right->par = toDelete->par;
|
||||||
}
|
}
|
||||||
parent = leftRotate(sibling);
|
parent = leftRotate(sibling);
|
||||||
|
|
||||||
// Check if the root is rotated
|
// Check if the root is rotated
|
||||||
if(parent->par == NULL){
|
if (parent->par == NULL)
|
||||||
|
{
|
||||||
*root = parent;
|
*root = parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -511,58 +606,71 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){
|
|||||||
checkForCase2(parent->left, 0, 0, root);
|
checkForCase2(parent->left, 0, 0, root);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// To delete a node from the tree
|
// To delete a node from the tree
|
||||||
void deleteNode(int val, Node** root){
|
void deleteNode(int val, Node **root)
|
||||||
Node* buffRoot = *root;
|
{
|
||||||
|
Node *buffRoot = *root;
|
||||||
|
|
||||||
//Search for the element in the tree
|
// Search for the element in the tree
|
||||||
while(1){
|
while (1)
|
||||||
|
{
|
||||||
if(val == buffRoot->val){
|
|
||||||
|
if (val == buffRoot->val)
|
||||||
|
{
|
||||||
// Node Found
|
// Node Found
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(val > buffRoot->val){
|
if (val > buffRoot->val)
|
||||||
if(buffRoot->right != NULL){
|
{
|
||||||
|
if (buffRoot->right != NULL)
|
||||||
|
{
|
||||||
buffRoot = buffRoot->right;
|
buffRoot = buffRoot->right;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
printf("Node Not Found!!!");
|
printf("Node Not Found!!!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
if(buffRoot->left != NULL){
|
{
|
||||||
|
if (buffRoot->left != NULL)
|
||||||
|
{
|
||||||
buffRoot = buffRoot->left;
|
buffRoot = buffRoot->left;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
printf("Node Not Found!!!");
|
printf("Node Not Found!!!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Node* toDelete = buffRoot;
|
Node *toDelete = buffRoot;
|
||||||
|
|
||||||
// Look for the leftmost of right node or right most of left node
|
// Look for the leftmost of right node or right most of left node
|
||||||
if(toDelete->left != NULL){
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete = toDelete->left;
|
toDelete = toDelete->left;
|
||||||
while(toDelete->right != NULL){
|
while (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete = toDelete->right;
|
toDelete = toDelete->right;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if(toDelete->right != NULL){
|
else if (toDelete->right != NULL)
|
||||||
|
{
|
||||||
toDelete = toDelete->right;
|
toDelete = toDelete->right;
|
||||||
while(toDelete->left != NULL){
|
while (toDelete->left != NULL)
|
||||||
|
{
|
||||||
toDelete = toDelete->left;
|
toDelete = toDelete->left;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(toDelete == *root){
|
if (toDelete == *root)
|
||||||
|
{
|
||||||
*root = NULL;
|
*root = NULL;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -572,28 +680,37 @@ void deleteNode(int val, Node** root){
|
|||||||
toDelete->val = val;
|
toDelete->val = val;
|
||||||
|
|
||||||
// Checking for case 1
|
// 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 it is a leaf
|
||||||
if(toDelete->left == NULL && toDelete->right == NULL){
|
if (toDelete->left == NULL && toDelete->right == NULL)
|
||||||
|
{
|
||||||
// Delete instantly
|
// Delete instantly
|
||||||
if(toDelete->par->left == toDelete){
|
if (toDelete->par->left == toDelete)
|
||||||
|
{
|
||||||
toDelete->par->left = NULL;
|
toDelete->par->left = NULL;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
toDelete->par->right = NULL;
|
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
|
// Check for the exitstence of left node
|
||||||
if(toDelete->left != NULL){
|
if (toDelete->left != NULL)
|
||||||
|
{
|
||||||
// The node should be right to its parent
|
// The node should be right to its parent
|
||||||
toDelete->par->right = toDelete->left;
|
toDelete->par->right = toDelete->left;
|
||||||
toDelete->left->par = toDelete->par;
|
toDelete->left->par = toDelete->par;
|
||||||
toDelete->left->color = 1;
|
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->par->left = toDelete->right;
|
||||||
toDelete->right->par = toDelete->par;
|
toDelete->right->par = toDelete->par;
|
||||||
toDelete->right->color = 1;
|
toDelete->right->color = 1;
|
||||||
@ -603,76 +720,85 @@ void deleteNode(int val, Node** root){
|
|||||||
// Remove the node from memory
|
// Remove the node from memory
|
||||||
free(toDelete);
|
free(toDelete);
|
||||||
}
|
}
|
||||||
else{ // Case 2
|
else
|
||||||
|
{ // Case 2
|
||||||
checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root);
|
checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void printInorder(Node* root){
|
void printInorder(Node *root)
|
||||||
if(root != NULL){
|
{
|
||||||
|
if (root != NULL)
|
||||||
|
{
|
||||||
printInorder(root->left);
|
printInorder(root->left);
|
||||||
printf("%d c-%d ", root->val, root->color);
|
printf("%d c-%d ", root->val, root->color);
|
||||||
printInorder(root->right);
|
printInorder(root->right);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void checkBlack(Node* temp,int c){
|
void checkBlack(Node *temp, int c)
|
||||||
if (temp==NULL){
|
{
|
||||||
printf("%d ",c);
|
if (temp == NULL)
|
||||||
return ;
|
{
|
||||||
|
printf("%d ", c);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (temp->color==0){
|
if (temp->color == 0)
|
||||||
|
{
|
||||||
c++;
|
c++;
|
||||||
}
|
}
|
||||||
checkBlack(temp->left,c);
|
checkBlack(temp->left, c);
|
||||||
checkBlack(temp->right,c);
|
checkBlack(temp->right, c);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(){
|
int main()
|
||||||
Node* root = NULL;
|
{
|
||||||
|
Node *root = NULL;
|
||||||
int scanValue, choice = 1;
|
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);
|
scanf("%d", &choice);
|
||||||
while(choice){
|
while (choice)
|
||||||
switch(choice){
|
{
|
||||||
case 1:
|
switch (choice)
|
||||||
printf("\n\nPlease Enter A Value to insert - ");
|
{
|
||||||
scanf("%d", &scanValue);
|
case 1:
|
||||||
if(root == NULL){
|
printf("\n\nPlease Enter A Value to insert - ");
|
||||||
root = newNode(scanValue, NULL);
|
scanf("%d", &scanValue);
|
||||||
root->color = 0;
|
if (root == NULL)
|
||||||
}
|
{
|
||||||
else{
|
root = newNode(scanValue, NULL);
|
||||||
insertNode(scanValue, &root);
|
root->color = 0;
|
||||||
}
|
}
|
||||||
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
|
else
|
||||||
break;
|
{
|
||||||
case 2:
|
insertNode(scanValue, &root);
|
||||||
printf("\n\nPlease Enter A Value to Delete - ");
|
}
|
||||||
scanf("%d", &scanValue);
|
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
|
||||||
deleteNode(scanValue, &root);
|
break;
|
||||||
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
|
case 2:
|
||||||
break;
|
printf("\n\nPlease Enter A Value to Delete - ");
|
||||||
case 3:
|
scanf("%d", &scanValue);
|
||||||
printf("\nInorder Traversel - ");
|
deleteNode(scanValue, &root);
|
||||||
printInorder(root);
|
printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue);
|
||||||
printf("\n\n");
|
break;
|
||||||
// checkBlack(root,0);
|
case 3:
|
||||||
// printf("\n");
|
printf("\nInorder Traversel - ");
|
||||||
break;
|
printInorder(root);
|
||||||
default:
|
printf("\n\n");
|
||||||
if(root != NULL){
|
// checkBlack(root,0);
|
||||||
printf("Root - %d\n", root->val);
|
// printf("\n");
|
||||||
}
|
break;
|
||||||
|
default:
|
||||||
|
if (root != NULL)
|
||||||
|
{
|
||||||
|
printf("Root - %d\n", root->val);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - ");
|
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - "
|
||||||
|
"Quit\n\nPlease Enter the Choice - ");
|
||||||
scanf("%d", &choice);
|
scanf("%d", &choice);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 32 12 50 53 1 2 3 4 5 6 7 8 9
|
// 32 12 50 53 1 2 3 4 5 6 7 8 9
|
||||||
|
@ -1,32 +1,30 @@
|
|||||||
|
#include "dict.h"
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include "dict.h"
|
|
||||||
|
|
||||||
|
|
||||||
/* simple constructor */
|
/* simple constructor */
|
||||||
Dictionary * create_dict(void)
|
Dictionary *create_dict(void)
|
||||||
{
|
{
|
||||||
Dictionary * p_dic = malloc(sizeof (Dictionary));
|
Dictionary *p_dic = malloc(sizeof(Dictionary));
|
||||||
if (p_dic)
|
if (p_dic)
|
||||||
{
|
{
|
||||||
p_dic->number_of_elements = 0;
|
p_dic->number_of_elements = 0;
|
||||||
|
|
||||||
/* initializes the elemens of the array with NULL-pointer */
|
/* initializes the elemens of the array with NULL-pointer */
|
||||||
for (int i = 0; i < MAXELEMENTS; i++)
|
for (int i = 0; i < MAXELEMENTS; i++)
|
||||||
{
|
{
|
||||||
p_dic->elements[i] = NULL;
|
p_dic->elements[i] = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
return p_dic;
|
return p_dic;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
printf("unable to create a dictionary\n");
|
printf("unable to create a dictionary\n");
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
utility function
|
utility function
|
||||||
sdbm hash algorithm
|
sdbm hash algorithm
|
||||||
@ -37,18 +35,18 @@ int get_hash(char s[])
|
|||||||
unsigned int hash_code = 0;
|
unsigned int hash_code = 0;
|
||||||
|
|
||||||
/* iterates over string at each character */
|
/* iterates over string at each character */
|
||||||
for (int counter = 0; s[counter]!='\0'; counter++)
|
for (int counter = 0; s[counter] != '\0'; counter++)
|
||||||
{
|
{
|
||||||
/* actual computing of the hash code */
|
/* 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. */
|
/* % modulo is for fitting the index in array. */
|
||||||
return hash_code % MAXELEMENTS;
|
return hash_code % MAXELEMENTS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int add_item_label(Dictionary *dic, char label[], void *item)
|
||||||
int add_item_label(Dictionary * dic,char label[],void * item)
|
|
||||||
{
|
{
|
||||||
unsigned int index = get_hash(label);
|
unsigned int index = get_hash(label);
|
||||||
|
|
||||||
@ -57,28 +55,26 @@ int add_item_label(Dictionary * dic,char label[],void * item)
|
|||||||
{
|
{
|
||||||
dic->elements[index] = item;
|
dic->elements[index] = item;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* error case */
|
/* error case */
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int add_item_index(Dictionary *dic, int index, void *item)
|
||||||
int add_item_index(Dictionary * dic , int index, void * item)
|
|
||||||
{
|
{
|
||||||
/* make sure whether this place is already given */
|
/* make sure whether this place is already given */
|
||||||
if (!dic->elements[index])
|
if (!dic->elements[index])
|
||||||
{
|
{
|
||||||
dic->elements[index] = item;
|
dic->elements[index] = item;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* error case */
|
/* error case */
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void *get_element_label(Dictionary *dict, char s[])
|
||||||
void * get_element_label(Dictionary * dict, char s[])
|
|
||||||
{
|
{
|
||||||
int index = get_hash(s);
|
int index = get_hash(s);
|
||||||
if (dict->elements[index])
|
if (dict->elements[index])
|
||||||
@ -90,20 +86,15 @@ void * get_element_label(Dictionary * dict, char s[])
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void *get_element_index(Dictionary *dict, int index)
|
||||||
void * get_element_index(Dictionary * dict, int index)
|
|
||||||
{
|
{
|
||||||
if (index >= 0 && index < MAXELEMENTS)
|
if (index >= 0 && index < MAXELEMENTS)
|
||||||
{
|
{
|
||||||
return dict->elements[index];
|
return dict->elements[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("index out of bounds!\n");
|
printf("index out of bounds!\n");
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void destroy(Dictionary *dict) { free(dict); }
|
||||||
void destroy(Dictionary * dict)
|
|
||||||
{
|
|
||||||
free(dict);
|
|
||||||
}
|
|
@ -1,6 +1,6 @@
|
|||||||
/*
|
/*
|
||||||
author: Christian Bender
|
author: Christian Bender
|
||||||
public interface for the dictionary.
|
public interface for the dictionary.
|
||||||
|
|
||||||
The dictionary prepares space for 1000 elements.
|
The dictionary prepares space for 1000 elements.
|
||||||
*/
|
*/
|
||||||
@ -14,13 +14,13 @@
|
|||||||
special data type called 'Dictionary'
|
special data type called 'Dictionary'
|
||||||
for generic use
|
for generic use
|
||||||
*/
|
*/
|
||||||
typedef struct Dict
|
typedef struct Dict
|
||||||
{
|
{
|
||||||
/*
|
/*
|
||||||
void* array for generic use of the dictionary.
|
void* array for generic use of the dictionary.
|
||||||
there actual saves the entries.
|
there actual saves the entries.
|
||||||
*/
|
*/
|
||||||
void * elements[MAXELEMENTS];
|
void *elements[MAXELEMENTS];
|
||||||
|
|
||||||
/* contains the number of elements in this dictionary */
|
/* contains the number of elements in this dictionary */
|
||||||
int number_of_elements;
|
int number_of_elements;
|
||||||
@ -28,41 +28,38 @@ typedef struct Dict
|
|||||||
} Dictionary;
|
} Dictionary;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
create_dict: is a simple constructor for creating
|
create_dict: is a simple constructor for creating
|
||||||
a dictionary and setting up the
|
a dictionary and setting up the
|
||||||
member field 'number_of_elements'
|
member field 'number_of_elements'
|
||||||
and prepares the inner array 'elements'
|
and prepares the inner array 'elements'
|
||||||
*/
|
*/
|
||||||
Dictionary * create_dict(void);
|
Dictionary *create_dict(void);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
add_item_label: adds item (void*) to the dictionary at given label
|
add_item_label: adds item (void*) to the dictionary at given label
|
||||||
returns 0 if adding was sucessful otherwise -1
|
returns 0 if adding was sucessful otherwise -1
|
||||||
*/
|
*/
|
||||||
int add_item_label(Dictionary *,char label[],void *);
|
int add_item_label(Dictionary *, char label[], void *);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
add_item_index: adds item (void*) to the dictionary at given index (int)
|
add_item_index: adds item (void*) to the dictionary at given index (int)
|
||||||
returns 0 if adding was sucessful otherwise -1
|
returns 0 if adding was sucessful otherwise -1
|
||||||
*/
|
*/
|
||||||
int add_item_index(Dictionary *, int index, 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 label
|
get_element: returns the element at given index
|
||||||
*/
|
*/
|
||||||
void * get_element_label(Dictionary *, char []);
|
void *get_element_index(Dictionary *, int);
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
get_element: returns the element at given index
|
|
||||||
*/
|
|
||||||
void * get_element_index(Dictionary *, int );
|
|
||||||
|
|
||||||
/*
|
|
||||||
simple destrcutor function
|
simple destrcutor function
|
||||||
*/
|
*/
|
||||||
void destroy(Dictionary *);
|
void destroy(Dictionary *);
|
||||||
|
|
||||||
|
|
||||||
#endif
|
#endif
|
@ -10,32 +10,32 @@
|
|||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
Dictionary * testObj1;
|
Dictionary *testObj1;
|
||||||
Dictionary * testObj2;
|
Dictionary *testObj2;
|
||||||
|
|
||||||
int value = 28;
|
int value = 28;
|
||||||
|
|
||||||
testObj1 = create_dict();
|
testObj1 = create_dict();
|
||||||
testObj2 = create_dict();
|
testObj2 = create_dict();
|
||||||
|
|
||||||
add_item_label(testObj1,"age",&value);
|
add_item_label(testObj1, "age", &value);
|
||||||
add_item_label(testObj2,"name","Christian");
|
add_item_label(testObj2, "name", "Christian");
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
test for function add_item_label
|
test for function add_item_label
|
||||||
|
|
||||||
attention:
|
attention:
|
||||||
The void* pointer must be convert into an int* pointer.
|
The void* pointer must be convert into an int* pointer.
|
||||||
After that you can dereference it.
|
After that you can dereference it.
|
||||||
*/
|
*/
|
||||||
printf("My age is %d\n",*((int *)get_element_label(testObj1,"age")));
|
printf("My age is %d\n", *((int *)get_element_label(testObj1, "age")));
|
||||||
printf("My name is %s\n",get_element_label(testObj2,"name"));
|
printf("My name is %s\n", get_element_label(testObj2, "name"));
|
||||||
|
|
||||||
/* test for function add_item_index */
|
/* test for function add_item_index */
|
||||||
if (!add_item_index(testObj1,0,&value))
|
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 */
|
/* error scenario */
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
#include <string.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include "dynamic_array.h"
|
#include "dynamic_array.h"
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
dynamic_array_t *init_dynamic_array()
|
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)
|
void *add(dynamic_array_t *da, const void *value)
|
||||||
{
|
{
|
||||||
if (da->size >= da->capacity) {
|
if (da->size >= da->capacity)
|
||||||
void **newItems = realloc(da->items, (da->capacity <<= 1) * sizeof(void **));
|
{
|
||||||
|
void **newItems =
|
||||||
|
realloc(da->items, (da->capacity <<= 1) * sizeof(void **));
|
||||||
free(da->items);
|
free(da->items);
|
||||||
|
|
||||||
da->items = newItems;
|
da->items = newItems;
|
||||||
@ -52,7 +54,8 @@ void delete (dynamic_array_t *da, const unsigned index)
|
|||||||
if (!contains(da->size, index))
|
if (!contains(da->size, index))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
for (unsigned i = index; i < da->size; i++) {
|
for (unsigned i = index; i < da->size; i++)
|
||||||
|
{
|
||||||
da->items[i] = da->items[i + 1];
|
da->items[i] = da->items[i + 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,7 +3,8 @@
|
|||||||
#define DEFAULT_CAPACITY 1 << 4
|
#define DEFAULT_CAPACITY 1 << 4
|
||||||
#define INDEX_OUT_OF_BOUNDS NULL
|
#define INDEX_OUT_OF_BOUNDS NULL
|
||||||
|
|
||||||
typedef struct dynamic_array {
|
typedef struct dynamic_array
|
||||||
|
{
|
||||||
void **items;
|
void **items;
|
||||||
unsigned size;
|
unsigned size;
|
||||||
unsigned capacity;
|
unsigned capacity;
|
||||||
|
@ -6,7 +6,8 @@ int main()
|
|||||||
{
|
{
|
||||||
dynamic_array_t *da = init_dynamic_array();
|
dynamic_array_t *da = init_dynamic_array();
|
||||||
|
|
||||||
for (int i = 1; i <= 50; i++) {
|
for (int i = 1; i <= 50; i++)
|
||||||
|
{
|
||||||
add(da, &i);
|
add(da, &i);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,7 +23,8 @@ int main()
|
|||||||
|
|
||||||
add(da, &another_value);
|
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));
|
printf("value %d\n", *(int *)get(da, i));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,63 +1,64 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#define SIZE 40
|
#define SIZE 40
|
||||||
//Assume max size of graph is 40 nodes
|
// Assume max size of graph is 40 nodes
|
||||||
struct queue {
|
struct queue
|
||||||
|
{
|
||||||
int items[SIZE];
|
int items[SIZE];
|
||||||
int front;
|
int front;
|
||||||
int rear;
|
int rear;
|
||||||
};
|
};
|
||||||
|
|
||||||
//Some declarations
|
// Some declarations
|
||||||
struct queue* createQueue();
|
struct queue *createQueue();
|
||||||
void enqueue(struct queue* q, int);
|
void enqueue(struct queue *q, int);
|
||||||
int dequeue(struct queue* q);
|
int dequeue(struct queue *q);
|
||||||
void display(struct queue* q);
|
void display(struct queue *q);
|
||||||
int isEmpty(struct queue* q);
|
int isEmpty(struct queue *q);
|
||||||
int pollQueue(struct queue* q);
|
int pollQueue(struct queue *q);
|
||||||
|
|
||||||
//Structure to create a graph node
|
// Structure to create a graph node
|
||||||
struct node
|
struct node
|
||||||
{
|
{
|
||||||
int vertex;
|
int vertex;
|
||||||
struct node* next;
|
struct node *next;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct node* createNode(int);
|
struct node *createNode(int);
|
||||||
|
|
||||||
//Graph data structure
|
// Graph data structure
|
||||||
struct Graph
|
struct Graph
|
||||||
{
|
{
|
||||||
int numVertices;
|
int numVertices;
|
||||||
struct node** adjLists;
|
struct node **adjLists;
|
||||||
int* visited;
|
int *visited;
|
||||||
};
|
};
|
||||||
struct Graph* createGraph(int vertices);
|
struct Graph *createGraph(int vertices);
|
||||||
void addEdge(struct Graph* graph, int src, int dest);
|
void addEdge(struct Graph *graph, int src, int dest);
|
||||||
void printGraph(struct Graph* graph);
|
void printGraph(struct Graph *graph);
|
||||||
void bfs(struct Graph* graph, int startVertex);
|
void bfs(struct Graph *graph, int startVertex);
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int vertices,edges,source,i,src,dst;
|
int vertices, edges, source, i, src, dst;
|
||||||
printf("Enter the number of vertices\n");
|
printf("Enter the number of vertices\n");
|
||||||
scanf("%d",&vertices);
|
scanf("%d", &vertices);
|
||||||
struct Graph* graph = createGraph(vertices);
|
struct Graph *graph = createGraph(vertices);
|
||||||
printf("Enter the number of edges\n");
|
printf("Enter the number of edges\n");
|
||||||
scanf("%d",&edges);
|
scanf("%d", &edges);
|
||||||
for(i=0; i<edges; i++)
|
for (i = 0; i < edges; i++)
|
||||||
{
|
{
|
||||||
printf("Edge %d \nEnter source: ",i+1);
|
printf("Edge %d \nEnter source: ", i + 1);
|
||||||
scanf("%d",&src);
|
scanf("%d", &src);
|
||||||
printf("Enter destination: ");
|
printf("Enter destination: ");
|
||||||
scanf("%d",&dst);
|
scanf("%d", &dst);
|
||||||
addEdge(graph, src, dst);
|
addEdge(graph, src, dst);
|
||||||
}
|
}
|
||||||
printf("Enter source of bfs\n");
|
printf("Enter source of bfs\n");
|
||||||
scanf("%d",&source);
|
scanf("%d", &source);
|
||||||
bfs(graph, source);
|
bfs(graph, source);
|
||||||
|
|
||||||
//Uncomment below part to get a ready-made example
|
// Uncomment below part to get a ready-made example
|
||||||
/*struct Graph* graph = createGraph(6);
|
/*struct Graph* graph = createGraph(6);
|
||||||
addEdge(graph, 0, 1);
|
addEdge(graph, 0, 1);
|
||||||
addEdge(graph, 0, 2);
|
addEdge(graph, 0, 2);
|
||||||
@ -67,122 +68,128 @@ int main()
|
|||||||
addEdge(graph, 2, 4);
|
addEdge(graph, 2, 4);
|
||||||
addEdge(graph, 3, 4);
|
addEdge(graph, 3, 4);
|
||||||
bfs(graph,0);*/
|
bfs(graph,0);*/
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
void bfs(struct Graph* graph, int startVertex)
|
void bfs(struct Graph *graph, int startVertex)
|
||||||
{
|
{
|
||||||
struct queue* q = createQueue();
|
struct queue *q = createQueue();
|
||||||
|
|
||||||
//Add to visited list and put in queue
|
// Add to visited list and put in queue
|
||||||
graph->visited[startVertex] = 1;
|
graph->visited[startVertex] = 1;
|
||||||
enqueue(q, startVertex);
|
enqueue(q, startVertex);
|
||||||
printf("Breadth first traversal from vertex %d is:\n",startVertex);
|
printf("Breadth first traversal from vertex %d is:\n", startVertex);
|
||||||
|
|
||||||
//Iterate while queue not empty
|
// Iterate while queue not empty
|
||||||
while(!isEmpty(q)){
|
while (!isEmpty(q))
|
||||||
printf("%d ",pollQueue(q));
|
{
|
||||||
|
printf("%d ", pollQueue(q));
|
||||||
int currentVertex = dequeue(q);
|
int currentVertex = dequeue(q);
|
||||||
|
|
||||||
struct node* temp = graph->adjLists[currentVertex];
|
struct node *temp = graph->adjLists[currentVertex];
|
||||||
//Add all unvisited neighbours of current vertex to queue to be printed next
|
// Add all unvisited neighbours of current vertex to queue to be printed
|
||||||
while(temp) {
|
// next
|
||||||
|
while (temp)
|
||||||
|
{
|
||||||
int adjVertex = temp->vertex;
|
int adjVertex = temp->vertex;
|
||||||
//Only add if neighbour is unvisited
|
// Only add if neighbour is unvisited
|
||||||
if(graph->visited[adjVertex] == 0){
|
if (graph->visited[adjVertex] == 0)
|
||||||
|
{
|
||||||
graph->visited[adjVertex] = 1;
|
graph->visited[adjVertex] = 1;
|
||||||
enqueue(q, adjVertex);
|
enqueue(q, adjVertex);
|
||||||
}
|
}
|
||||||
temp = temp->next;
|
temp = temp->next;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Memory for a graph node
|
// Memory for a graph node
|
||||||
struct node* createNode(int v)
|
struct node *createNode(int v)
|
||||||
{
|
{
|
||||||
struct node* newNode = malloc(sizeof(struct node));
|
struct node *newNode = malloc(sizeof(struct node));
|
||||||
newNode->vertex = v;
|
newNode->vertex = v;
|
||||||
newNode->next = NULL;
|
newNode->next = NULL;
|
||||||
return newNode;
|
return newNode;
|
||||||
}
|
}
|
||||||
//Allocates memory for graph data structure, in adjacency list format
|
// Allocates memory for graph data structure, in adjacency list format
|
||||||
struct Graph* createGraph(int vertices)
|
struct Graph *createGraph(int vertices)
|
||||||
{
|
{
|
||||||
struct Graph* graph = malloc(sizeof(struct Graph));
|
struct Graph *graph = malloc(sizeof(struct Graph));
|
||||||
graph->numVertices = vertices;
|
graph->numVertices = vertices;
|
||||||
|
|
||||||
graph->adjLists = malloc(vertices * sizeof(struct node*));
|
graph->adjLists = malloc(vertices * sizeof(struct node *));
|
||||||
graph->visited = malloc(vertices * sizeof(int));
|
graph->visited = malloc(vertices * sizeof(int));
|
||||||
|
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < vertices; i++) {
|
for (i = 0; i < vertices; i++)
|
||||||
|
{
|
||||||
graph->adjLists[i] = NULL;
|
graph->adjLists[i] = NULL;
|
||||||
graph->visited[i] = 0;
|
graph->visited[i] = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return graph;
|
return graph;
|
||||||
}
|
}
|
||||||
//Adds bidirectional edge to graph
|
// Adds bidirectional edge to graph
|
||||||
void addEdge(struct Graph* graph, int src, int dest)
|
void addEdge(struct Graph *graph, int src, int dest)
|
||||||
{
|
{
|
||||||
// Add edge from src to dest
|
// Add edge from src to dest
|
||||||
struct node* newNode = createNode(dest);
|
struct node *newNode = createNode(dest);
|
||||||
newNode->next = graph->adjLists[src];
|
newNode->next = graph->adjLists[src];
|
||||||
graph->adjLists[src] = newNode;
|
graph->adjLists[src] = newNode;
|
||||||
|
|
||||||
// Add edge from dest to src; comment it out for directed graph
|
// Add edge from dest to src; comment it out for directed graph
|
||||||
newNode = createNode(src);
|
newNode = createNode(src);
|
||||||
newNode->next = graph->adjLists[dest];
|
newNode->next = graph->adjLists[dest];
|
||||||
graph->adjLists[dest] = newNode;
|
graph->adjLists[dest] = newNode;
|
||||||
}
|
}
|
||||||
//Allocates memory for our queue data structure
|
// Allocates memory for our queue data structure
|
||||||
struct queue* createQueue()
|
struct queue *createQueue()
|
||||||
{
|
{
|
||||||
struct queue* q = malloc(sizeof(struct queue));
|
struct queue *q = malloc(sizeof(struct queue));
|
||||||
q->front = -1;
|
q->front = -1;
|
||||||
q->rear = -1;
|
q->rear = -1;
|
||||||
return q;
|
return q;
|
||||||
}
|
}
|
||||||
//Checks for empty queue
|
// Checks for empty queue
|
||||||
int isEmpty(struct queue* q)
|
int isEmpty(struct queue *q)
|
||||||
{
|
{
|
||||||
if(q->rear == -1)
|
if (q->rear == -1)
|
||||||
return 1;
|
return 1;
|
||||||
else
|
else
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
//Inserts item at start of queue
|
// Inserts item at start of queue
|
||||||
void enqueue(struct queue* q, int value)
|
void enqueue(struct queue *q, int value)
|
||||||
{
|
{
|
||||||
if(q->rear == SIZE-1)
|
if (q->rear == SIZE - 1)
|
||||||
printf("\nQueue is Full!!");
|
printf("\nQueue is Full!!");
|
||||||
else {
|
else
|
||||||
if(q->front == -1)
|
{
|
||||||
|
if (q->front == -1)
|
||||||
q->front = 0;
|
q->front = 0;
|
||||||
q->rear++;
|
q->rear++;
|
||||||
q->items[q->rear] = value;
|
q->items[q->rear] = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Returns item at front of queue and removes it from queue
|
// Returns item at front of queue and removes it from queue
|
||||||
int dequeue(struct queue* q)
|
int dequeue(struct queue *q)
|
||||||
{
|
{
|
||||||
int item;
|
int item;
|
||||||
if(isEmpty(q)){
|
if (isEmpty(q))
|
||||||
|
{
|
||||||
printf("Queue is empty");
|
printf("Queue is empty");
|
||||||
item = -1;
|
item = -1;
|
||||||
}
|
}
|
||||||
else{
|
else
|
||||||
|
{
|
||||||
item = q->items[q->front];
|
item = q->items[q->front];
|
||||||
q->front++;
|
q->front++;
|
||||||
if(q->front > q->rear){
|
if (q->front > q->rear)
|
||||||
|
{
|
||||||
q->front = q->rear = -1;
|
q->front = q->rear = -1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return item;
|
return item;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Returns element at front of queue
|
// Returns element at front of queue
|
||||||
int pollQueue(struct queue *q)
|
int pollQueue(struct queue *q) { return q->items[q->front]; }
|
||||||
{
|
|
||||||
return q->items[q->front];
|
|
||||||
}
|
|
||||||
|
@ -1,130 +1,140 @@
|
|||||||
#include<stdio.h>
|
#include <limits.h>
|
||||||
#include<stdlib.h>
|
#include <stdio.h>
|
||||||
#include<limits.h>
|
#include <stdlib.h>
|
||||||
#include<string.h>
|
#include <string.h>
|
||||||
|
|
||||||
//Structure for storing edge
|
// Structure for storing edge
|
||||||
struct Edge{
|
struct Edge
|
||||||
int src,dst,weight;
|
{
|
||||||
|
int src, dst, weight;
|
||||||
};
|
};
|
||||||
|
|
||||||
//Structure for storing a graph
|
// Structure for storing a graph
|
||||||
struct Graph{
|
struct Graph
|
||||||
int vertexNum;
|
{
|
||||||
int edgeNum;
|
int vertexNum;
|
||||||
struct Edge* edges;
|
int edgeNum;
|
||||||
|
struct Edge *edges;
|
||||||
};
|
};
|
||||||
|
|
||||||
//Constructs a graph with V vertices and E 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->vertexNum = V;
|
||||||
G->edges = (struct Edge*) malloc(E * sizeof(struct Edge));
|
G->edgeNum = E;
|
||||||
|
G->edges = (struct Edge *)malloc(E * sizeof(struct Edge));
|
||||||
}
|
}
|
||||||
|
|
||||||
//Adds the given edge to the graph
|
// 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;
|
static int ind;
|
||||||
newEdge.src = src;
|
struct Edge newEdge;
|
||||||
newEdge.dst = dst;
|
newEdge.src = src;
|
||||||
newEdge.weight = weight;
|
newEdge.dst = dst;
|
||||||
G->edges[ind++]= newEdge;
|
newEdge.weight = weight;
|
||||||
|
G->edges[ind++] = newEdge;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Utility function to find minimum distance vertex in mdist
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
minVal = mdist[i];
|
||||||
|
minInd = i;
|
||||||
|
}
|
||||||
|
|
||||||
//Utility function to find minimum distance vertex in mdist
|
return minInd;
|
||||||
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){
|
|
||||||
minVal = mdist[i];
|
|
||||||
minInd = i;
|
|
||||||
}
|
|
||||||
|
|
||||||
return minInd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Utility function to print distances
|
// 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++){
|
printf("\nVertex Distance\n");
|
||||||
if(dist[i] != INT_MAX)
|
for (int i = 0; i < V; i++)
|
||||||
printf("%d\t%d\n",i,dist[i]);
|
{
|
||||||
else
|
if (dist[i] != INT_MAX)
|
||||||
printf("%d\tINF",i);
|
printf("%d\t%d\n", i, dist[i]);
|
||||||
}
|
else
|
||||||
|
printf("%d\tINF", i);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//The main function that finds the shortest path from given source
|
// The main function that finds the shortest path from given source
|
||||||
//to all other vertices using Bellman-Ford.It also detects negative
|
// to all other vertices using Bellman-Ford.It also detects negative
|
||||||
//weight cycle
|
// 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 V = graph->vertexNum;
|
||||||
int dist[V];
|
int E = graph->edgeNum;
|
||||||
|
int dist[V];
|
||||||
|
|
||||||
//Initialize distances array as INF for all except source
|
// Initialize distances array as INF for all except source
|
||||||
//Intialize source as zero
|
// Intialize source as zero
|
||||||
for(int i=0; i<V; i++)
|
for (int i = 0; i < V; i++)
|
||||||
dist[i] = INT_MAX;
|
dist[i] = INT_MAX;
|
||||||
dist[src] = 0;
|
dist[src] = 0;
|
||||||
|
|
||||||
//Calculate shortest path distance from source to all edges
|
// Calculate shortest path distance from source to all edges
|
||||||
//A path can contain maximum (|V|-1) edges
|
// A path can contain maximum (|V|-1) edges
|
||||||
for(int i=0; i<=V-1; i++)
|
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 u = graph->edges[j].src;
|
||||||
int w = graph->edges[j].weight;
|
int v = graph->edges[j].dst;
|
||||||
|
int w = graph->edges[j].weight;
|
||||||
if(dist[u]!=INT_MAX && dist[u] + w < dist[v])
|
|
||||||
dist[v] = dist[u] + w;
|
|
||||||
}
|
|
||||||
|
|
||||||
//Iterate inner loop once more to check for negative cycle
|
|
||||||
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.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
print(dist, V);
|
if (dist[u] != INT_MAX && dist[u] + w < dist[v])
|
||||||
|
dist[v] = dist[u] + w;
|
||||||
return;
|
}
|
||||||
|
|
||||||
|
// Iterate inner loop once more to check for negative cycle
|
||||||
|
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.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
print(dist, V);
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Driver Function
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
int V, E, gsrc;
|
||||||
|
int src, dst, weight;
|
||||||
|
struct Graph G;
|
||||||
|
printf("Enter number of vertices: ");
|
||||||
|
scanf("%d", &V);
|
||||||
|
printf("Enter number of edges: ");
|
||||||
|
scanf("%d", &E);
|
||||||
|
createGraph(&G, V, E);
|
||||||
|
for (int i = 0; i < E; i++)
|
||||||
|
{
|
||||||
|
printf("\nEdge %d \nEnter source: ", i + 1);
|
||||||
|
scanf("%d", &src);
|
||||||
|
printf("Enter destination: ");
|
||||||
|
scanf("%d", &dst);
|
||||||
|
printf("Enter weight: ");
|
||||||
|
scanf("%d", &weight);
|
||||||
|
addEdge(&G, src, dst, weight);
|
||||||
|
}
|
||||||
|
printf("\nEnter source:");
|
||||||
|
scanf("%d", &gsrc);
|
||||||
|
BellmanFord(&G, gsrc);
|
||||||
|
|
||||||
|
return 0;
|
||||||
//Driver Function
|
|
||||||
int main(){
|
|
||||||
int V,E,gsrc;
|
|
||||||
int src,dst,weight;
|
|
||||||
struct Graph G;
|
|
||||||
printf("Enter number of vertices: ");
|
|
||||||
scanf("%d",&V);
|
|
||||||
printf("Enter number of edges: ");
|
|
||||||
scanf("%d",&E);
|
|
||||||
createGraph(&G,V,E);
|
|
||||||
for(int i=0; i<E; i++){
|
|
||||||
printf("\nEdge %d \nEnter source: ",i+1);
|
|
||||||
scanf("%d",&src);
|
|
||||||
printf("Enter destination: ");
|
|
||||||
scanf("%d",&dst);
|
|
||||||
printf("Enter weight: ");
|
|
||||||
scanf("%d",&weight);
|
|
||||||
addEdge(&G, src, dst, weight);
|
|
||||||
}
|
|
||||||
printf("\nEnter source:");
|
|
||||||
scanf("%d",&gsrc);
|
|
||||||
BellmanFord(&G,gsrc);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,48 +1,50 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
//A vertex of the graph
|
// A vertex of the graph
|
||||||
struct node
|
struct node
|
||||||
{
|
{
|
||||||
int vertex;
|
int vertex;
|
||||||
struct node* next;
|
struct node *next;
|
||||||
};
|
};
|
||||||
//Some declarations
|
// Some declarations
|
||||||
struct node* createNode(int v);
|
struct node *createNode(int v);
|
||||||
struct Graph
|
struct Graph
|
||||||
{
|
{
|
||||||
int numVertices;
|
int numVertices;
|
||||||
int* visited;
|
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);
|
struct Graph *createGraph(int);
|
||||||
void addEdge(struct Graph*, int, int);
|
void addEdge(struct Graph *, int, int);
|
||||||
void printGraph(struct Graph*);
|
void printGraph(struct Graph *);
|
||||||
void dfs(struct Graph*, int);
|
void dfs(struct Graph *, int);
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int vertices,edges,source,i,src,dst;
|
int vertices, edges, source, i, src, dst;
|
||||||
printf("Enter the number of vertices\n");
|
printf("Enter the number of vertices\n");
|
||||||
scanf("%d",&vertices);
|
scanf("%d", &vertices);
|
||||||
struct Graph* graph = createGraph(vertices);
|
struct Graph *graph = createGraph(vertices);
|
||||||
printf("Enter the number of edges\n");
|
printf("Enter the number of edges\n");
|
||||||
scanf("%d",&edges);
|
scanf("%d", &edges);
|
||||||
for(i=0; i<edges; i++)
|
for (i = 0; i < edges; i++)
|
||||||
{
|
{
|
||||||
printf("Edge %d \nEnter source: ",i+1);
|
printf("Edge %d \nEnter source: ", i + 1);
|
||||||
scanf("%d",&src);
|
scanf("%d", &src);
|
||||||
printf("Enter destination: ");
|
printf("Enter destination: ");
|
||||||
scanf("%d",&dst);
|
scanf("%d", &dst);
|
||||||
addEdge(graph, src, dst);
|
addEdge(graph, src, dst);
|
||||||
}
|
}
|
||||||
printf("Enter source of DFS\n");
|
printf("Enter source of DFS\n");
|
||||||
scanf("%d",&source);
|
scanf("%d", &source);
|
||||||
printf("DFS from %d is:\n",source);
|
printf("DFS from %d is:\n", source);
|
||||||
dfs(graph, source);
|
dfs(graph, source);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
|
|
||||||
//Uncomment below part to get a ready-made example
|
// Uncomment below part to get a ready-made example
|
||||||
/*struct Graph* graph = createGraph(4);
|
/*struct Graph* graph = createGraph(4);
|
||||||
addEdge(graph, 0, 1);
|
addEdge(graph, 0, 1);
|
||||||
addEdge(graph, 0, 2);
|
addEdge(graph, 0, 2);
|
||||||
@ -50,73 +52,77 @@ int main()
|
|||||||
addEdge(graph, 2, 3);
|
addEdge(graph, 2, 3);
|
||||||
printf("DFS from 0 is:\n");
|
printf("DFS from 0 is:\n");
|
||||||
dfs(graph,0);
|
dfs(graph,0);
|
||||||
printf("\n");*/
|
printf("\n");*/
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
//Recursive dfs approach
|
// 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;
|
|
||||||
|
|
||||||
//Add vertex to visited list and print it
|
|
||||||
graph->visited[vertex] = 1;
|
|
||||||
printf("%d ", vertex);
|
|
||||||
|
|
||||||
//Recursively call the dfs function on all unvisited neighbours
|
|
||||||
while(temp!=NULL) {
|
|
||||||
int connectedVertex = temp->vertex;
|
|
||||||
if(graph->visited[connectedVertex] == 0) {
|
|
||||||
dfs(graph, connectedVertex);
|
|
||||||
}
|
|
||||||
temp = temp->next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//Allocate memory for a node
|
|
||||||
struct node* createNode(int v)
|
|
||||||
{
|
{
|
||||||
struct node* newNode = malloc(sizeof(struct node));
|
struct node *adjList = graph->adjLists[vertex];
|
||||||
|
struct node *temp = adjList;
|
||||||
|
|
||||||
|
// Add vertex to visited list and print it
|
||||||
|
graph->visited[vertex] = 1;
|
||||||
|
printf("%d ", vertex);
|
||||||
|
|
||||||
|
// Recursively call the dfs function on all unvisited neighbours
|
||||||
|
while (temp != NULL)
|
||||||
|
{
|
||||||
|
int connectedVertex = temp->vertex;
|
||||||
|
if (graph->visited[connectedVertex] == 0)
|
||||||
|
{
|
||||||
|
dfs(graph, connectedVertex);
|
||||||
|
}
|
||||||
|
temp = temp->next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Allocate memory for a node
|
||||||
|
struct node *createNode(int v)
|
||||||
|
{
|
||||||
|
struct node *newNode = malloc(sizeof(struct node));
|
||||||
newNode->vertex = v;
|
newNode->vertex = v;
|
||||||
newNode->next = NULL;
|
newNode->next = NULL;
|
||||||
return newNode;
|
return newNode;
|
||||||
}
|
}
|
||||||
//Allocate memory for the entire graph structure
|
// Allocate memory for the entire graph structure
|
||||||
struct Graph* createGraph(int vertices)
|
struct Graph *createGraph(int vertices)
|
||||||
{
|
{
|
||||||
struct Graph* graph = malloc(sizeof(struct Graph));
|
struct Graph *graph = malloc(sizeof(struct Graph));
|
||||||
graph->numVertices = vertices;
|
graph->numVertices = vertices;
|
||||||
|
|
||||||
graph->adjLists = malloc(vertices * sizeof(struct node*));
|
graph->adjLists = malloc(vertices * sizeof(struct node *));
|
||||||
|
|
||||||
graph->visited = malloc(vertices * sizeof(int));
|
graph->visited = malloc(vertices * sizeof(int));
|
||||||
|
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < vertices; i++) {
|
for (i = 0; i < vertices; i++)
|
||||||
|
{
|
||||||
graph->adjLists[i] = NULL;
|
graph->adjLists[i] = NULL;
|
||||||
graph->visited[i] = 0;
|
graph->visited[i] = 0;
|
||||||
}
|
}
|
||||||
return graph;
|
return graph;
|
||||||
}
|
}
|
||||||
//Creates a bidirectional graph
|
// Creates a bidirectional graph
|
||||||
void addEdge(struct Graph* graph, int src, int dest)
|
void addEdge(struct Graph *graph, int src, int dest)
|
||||||
{
|
{
|
||||||
// Add edge from src to dest
|
// Add edge from src to dest
|
||||||
struct node* newNode = createNode(dest);
|
struct node *newNode = createNode(dest);
|
||||||
newNode->next = graph->adjLists[src];
|
newNode->next = graph->adjLists[src];
|
||||||
graph->adjLists[src] = newNode;
|
graph->adjLists[src] = newNode;
|
||||||
|
|
||||||
// Add edge from dest to src
|
// Add edge from dest to src
|
||||||
newNode = createNode(src);
|
newNode = createNode(src);
|
||||||
newNode->next = graph->adjLists[dest];
|
newNode->next = graph->adjLists[dest];
|
||||||
graph->adjLists[dest] = newNode;
|
graph->adjLists[dest] = newNode;
|
||||||
}
|
}
|
||||||
//Utility function to see state of graph at a given time
|
// Utility function to see state of graph at a given time
|
||||||
void printGraph(struct Graph* graph)
|
void printGraph(struct Graph *graph)
|
||||||
{
|
{
|
||||||
int v;
|
int v;
|
||||||
for (v = 0; v < graph->numVertices; v++)
|
for (v = 0; v < graph->numVertices; v++)
|
||||||
{
|
{
|
||||||
struct node* temp = graph->adjLists[v];
|
struct node *temp = graph->adjLists[v];
|
||||||
printf("\n Adjacency list of vertex %d\n ", v);
|
printf("\n Adjacency list of vertex %d\n ", v);
|
||||||
while (temp)
|
while (temp)
|
||||||
{
|
{
|
||||||
|
@ -1,114 +1,121 @@
|
|||||||
#include<stdio.h>
|
#include <limits.h>
|
||||||
#include<stdlib.h>
|
#include <stdio.h>
|
||||||
#include<limits.h>
|
#include <stdlib.h>
|
||||||
#include<string.h>
|
#include <string.h>
|
||||||
|
|
||||||
|
// Structure for storing a graph
|
||||||
//Structure for storing a graph
|
struct Graph
|
||||||
struct Graph{
|
{
|
||||||
int vertexNum;
|
int vertexNum;
|
||||||
int** edges;
|
int **edges;
|
||||||
};
|
};
|
||||||
|
|
||||||
//Constructs a graph with V vertices and E 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*));
|
G->vertexNum = V;
|
||||||
for(int i=0; i<V; i++){
|
G->edges = (int **)malloc(V * sizeof(int *));
|
||||||
G->edges[i] = (int*) malloc(V * sizeof(int));
|
for (int i = 0; i < V; i++)
|
||||||
for(int j=0; j<V; j++)
|
{
|
||||||
G->edges[i][j] = INT_MAX;
|
G->edges[i] = (int *)malloc(V * sizeof(int));
|
||||||
G->edges[i][i] = 0;
|
for (int j = 0; j < V; j++)
|
||||||
}
|
G->edges[i][j] = INT_MAX;
|
||||||
|
G->edges[i][i] = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Adds the given edge to the graph
|
// 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;
|
{
|
||||||
|
G->edges[src][dst] = weight;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Utility function to find minimum distance vertex in mdist
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
minVal = mdist[i];
|
||||||
|
minInd = i;
|
||||||
|
}
|
||||||
|
|
||||||
//Utility function to find minimum distance vertex in mdist
|
return minInd;
|
||||||
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){
|
|
||||||
minVal = mdist[i];
|
|
||||||
minInd = i;
|
|
||||||
}
|
|
||||||
|
|
||||||
return minInd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Utility function to print distances
|
// 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++){
|
printf("\nVertex Distance\n");
|
||||||
if(dist[i] != INT_MAX)
|
for (int i = 0; i < V; i++)
|
||||||
printf("%d\t%d\n",i,dist[i]);
|
{
|
||||||
else
|
if (dist[i] != INT_MAX)
|
||||||
printf("%d\tINF",i);
|
printf("%d\t%d\n", i, dist[i]);
|
||||||
}
|
else
|
||||||
|
printf("%d\tINF", i);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//The main function that finds the shortest path from given source
|
// 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
|
// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative
|
||||||
//weights
|
// 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 V = graph->vertexNum;
|
||||||
int vset[V]; // vset[i] is true if the vertex i included
|
int mdist[V]; // Stores updated distances to vertex
|
||||||
// in the shortest path tree
|
int vset[V]; // vset[i] is true if the vertex i included
|
||||||
|
// in the shortest path tree
|
||||||
|
|
||||||
//Initialise mdist and vset. Set distance of source as zero
|
// Initialise mdist and vset. Set distance of source as zero
|
||||||
for(int i=0; i<V; i++)
|
for (int i = 0; i < V; i++)
|
||||||
mdist[i] = INT_MAX, vset[i] = 0;
|
mdist[i] = INT_MAX, vset[i] = 0;
|
||||||
|
|
||||||
mdist[src] = 0;
|
|
||||||
|
|
||||||
//iterate to find shortest path
|
|
||||||
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])
|
|
||||||
mdist[v] = mdist[u] + graph->edges[u][v];
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
print(mdist, V);
|
mdist[src] = 0;
|
||||||
|
|
||||||
return;
|
// iterate to find shortest path
|
||||||
|
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])
|
||||||
|
mdist[v] = mdist[u] + graph->edges[u][v];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
print(mdist, V);
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Driver Function
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
int V, E, gsrc;
|
||||||
|
int src, dst, weight;
|
||||||
|
struct Graph G;
|
||||||
|
printf("Enter number of vertices: ");
|
||||||
|
scanf("%d", &V);
|
||||||
|
printf("Enter number of edges: ");
|
||||||
|
scanf("%d", &E);
|
||||||
|
createGraph(&G, V);
|
||||||
|
for (int i = 0; i < E; i++)
|
||||||
|
{
|
||||||
|
printf("\nEdge %d \nEnter source: ", i + 1);
|
||||||
|
scanf("%d", &src);
|
||||||
|
printf("Enter destination: ");
|
||||||
|
scanf("%d", &dst);
|
||||||
|
printf("Enter weight: ");
|
||||||
|
scanf("%d", &weight);
|
||||||
|
addEdge(&G, src, dst, weight);
|
||||||
|
}
|
||||||
|
printf("\nEnter source:");
|
||||||
|
scanf("%d", &gsrc);
|
||||||
|
Dijkstra(&G, gsrc);
|
||||||
|
|
||||||
|
return 0;
|
||||||
//Driver Function
|
|
||||||
int main(){
|
|
||||||
int V,E,gsrc;
|
|
||||||
int src,dst,weight;
|
|
||||||
struct Graph G;
|
|
||||||
printf("Enter number of vertices: ");
|
|
||||||
scanf("%d",&V);
|
|
||||||
printf("Enter number of edges: ");
|
|
||||||
scanf("%d",&E);
|
|
||||||
createGraph(&G,V);
|
|
||||||
for(int i=0; i<E; i++){
|
|
||||||
printf("\nEdge %d \nEnter source: ",i+1);
|
|
||||||
scanf("%d",&src);
|
|
||||||
printf("Enter destination: ");
|
|
||||||
scanf("%d",&dst);
|
|
||||||
printf("Enter weight: ");
|
|
||||||
scanf("%d",&weight);
|
|
||||||
addEdge(&G, src, dst, weight);
|
|
||||||
}
|
|
||||||
printf("\nEnter source:");
|
|
||||||
scanf("%d",&gsrc);
|
|
||||||
Dijkstra(&G,gsrc);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,104 +1,112 @@
|
|||||||
#include<stdio.h>
|
#include <limits.h>
|
||||||
#include<stdlib.h>
|
#include <stdio.h>
|
||||||
#include<limits.h>
|
#include <stdlib.h>
|
||||||
#include<string.h>
|
#include <string.h>
|
||||||
|
|
||||||
|
// Structure for storing a graph
|
||||||
//Structure for storing a graph
|
struct Graph
|
||||||
struct Graph{
|
{
|
||||||
int vertexNum;
|
int vertexNum;
|
||||||
int** edges;
|
int **edges;
|
||||||
};
|
};
|
||||||
|
|
||||||
//Constructs a graph with V vertices and E 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*));
|
G->vertexNum = V;
|
||||||
for(int i=0; i<V; i++){
|
G->edges = (int **)malloc(V * sizeof(int *));
|
||||||
G->edges[i] = (int*) malloc(V * sizeof(int));
|
for (int i = 0; i < V; i++)
|
||||||
for(int j=0; j<V; j++)
|
{
|
||||||
G->edges[i][j] = INT_MAX;
|
G->edges[i] = (int *)malloc(V * sizeof(int));
|
||||||
G->edges[i][i] = 0;
|
for (int j = 0; j < V; j++)
|
||||||
}
|
G->edges[i][j] = INT_MAX;
|
||||||
|
G->edges[i][i] = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Adds the given edge to the graph
|
// 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;
|
{
|
||||||
|
G->edges[src][dst] = weight;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Utility function to print distances
|
||||||
|
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++)
|
||||||
|
{
|
||||||
|
|
||||||
//Utility function to print distances
|
if (dist[i * V + j] != INT_MAX)
|
||||||
void print(int dist[], int V){
|
printf("%d\t", dist[i * V + j]);
|
||||||
printf("\nThe Distance matrix for Floyd - Warshall\n");
|
else
|
||||||
for(int i = 0; i < V; i++){
|
printf("INF\t");
|
||||||
for(int j=0; j<V; j++){
|
}
|
||||||
|
printf("\n");
|
||||||
if(dist[i*V+j] != INT_MAX)
|
}
|
||||||
printf("%d\t",dist[i*V+j]);
|
|
||||||
else
|
|
||||||
printf("INF\t");
|
|
||||||
}
|
|
||||||
printf("\n");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//The main function that finds the shortest path from a vertex
|
// The main function that finds the shortest path from a vertex
|
||||||
//to all other vertices using Floyd-Warshall Algorithm.
|
// 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];
|
int V = graph->vertexNum;
|
||||||
|
int dist[V][V];
|
||||||
//Initialise distance array
|
|
||||||
for(int i=0; i<V; i++)
|
|
||||||
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
|
|
||||||
|
|
||||||
for(int i=0; i<V; i++)
|
// Initialise distance array
|
||||||
//Choose a source vertex for given intermediate
|
for (int i = 0; i < V; i++)
|
||||||
|
for (int j = 0; j < V; j++)
|
||||||
|
dist[i][j] = graph->edges[i][j];
|
||||||
|
|
||||||
for(int j=0; j<V; j++)
|
// Calculate distances
|
||||||
//Choose a destination vertex for above source vertex
|
for (int k = 0; k < V; k++)
|
||||||
|
// Choose an intermediate vertex
|
||||||
|
|
||||||
if(dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j])
|
for (int i = 0; i < V; i++)
|
||||||
//If the distance through intermediate vertex is less than direct edge then update value in distance array
|
// Choose a source vertex for given intermediate
|
||||||
dist[i][j] = dist[i][k] + dist[k][j];
|
|
||||||
|
|
||||||
|
for (int j = 0; j < V; j++)
|
||||||
//Convert 2d array to 1d array for print
|
// Choose a destination vertex for above source vertex
|
||||||
int dist1d[V*V];
|
|
||||||
for(int i=0; i<V; i++)
|
|
||||||
for(int j=0; j<V; j++)
|
|
||||||
dist1d[i*V+j] = dist[i][j];
|
|
||||||
|
|
||||||
print(dist1d,V);
|
|
||||||
}
|
|
||||||
|
|
||||||
//Driver Function
|
if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX &&
|
||||||
int main(){
|
dist[i][k] + dist[k][j] < dist[i][j])
|
||||||
int V,E;
|
// If the distance through intermediate vertex is less than
|
||||||
int src,dst,weight;
|
// direct edge then update value in distance array
|
||||||
struct Graph G;
|
dist[i][j] = dist[i][k] + dist[k][j];
|
||||||
printf("Enter number of vertices: ");
|
|
||||||
scanf("%d",&V);
|
|
||||||
printf("Enter number of edges: ");
|
|
||||||
scanf("%d",&E);
|
|
||||||
createGraph(&G,V);
|
|
||||||
for(int i=0; i<E; i++){
|
|
||||||
printf("\nEdge %d \nEnter source: ",i+1);
|
|
||||||
scanf("%d",&src);
|
|
||||||
printf("Enter destination: ");
|
|
||||||
scanf("%d",&dst);
|
|
||||||
printf("Enter weight: ");
|
|
||||||
scanf("%d",&weight);
|
|
||||||
addEdge(&G, src, dst, weight);
|
|
||||||
}
|
|
||||||
FloydWarshall(&G);
|
|
||||||
|
|
||||||
return 0;
|
// Convert 2d array to 1d array for print
|
||||||
|
int dist1d[V * V];
|
||||||
|
for (int i = 0; i < V; i++)
|
||||||
|
for (int j = 0; j < V; j++)
|
||||||
|
dist1d[i * V + j] = dist[i][j];
|
||||||
|
|
||||||
|
print(dist1d, V);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Driver Function
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
int V, E;
|
||||||
|
int src, dst, weight;
|
||||||
|
struct Graph G;
|
||||||
|
printf("Enter number of vertices: ");
|
||||||
|
scanf("%d", &V);
|
||||||
|
printf("Enter number of edges: ");
|
||||||
|
scanf("%d", &E);
|
||||||
|
createGraph(&G, V);
|
||||||
|
for (int i = 0; i < E; i++)
|
||||||
|
{
|
||||||
|
printf("\nEdge %d \nEnter source: ", i + 1);
|
||||||
|
scanf("%d", &src);
|
||||||
|
printf("Enter destination: ");
|
||||||
|
scanf("%d", &dst);
|
||||||
|
printf("Enter weight: ");
|
||||||
|
scanf("%d", &weight);
|
||||||
|
addEdge(&G, src, dst, weight);
|
||||||
|
}
|
||||||
|
FloydWarshall(&G);
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -1,102 +1,118 @@
|
|||||||
// Graph ADT
|
// Graph ADT
|
||||||
// Adjacency Matrix Representation
|
// Adjacency Matrix Representation
|
||||||
#include "Graph.h"
|
#include "Graph.h"
|
||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
#include <stdlib.h>
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
typedef struct GraphRep {
|
typedef struct GraphRep
|
||||||
int **edges; // adjacency matrix
|
{
|
||||||
int nV; // #vertices
|
int **edges; // adjacency matrix
|
||||||
int nE; // #edges
|
int nV; // #vertices
|
||||||
|
int nE; // #edges
|
||||||
} GraphRep;
|
} GraphRep;
|
||||||
|
|
||||||
Graph newGraph(int V) {
|
Graph newGraph(int V)
|
||||||
assert(V >= 0);
|
{
|
||||||
int i;
|
assert(V >= 0);
|
||||||
|
int i;
|
||||||
|
|
||||||
Graph g = malloc(sizeof(GraphRep));
|
Graph g = malloc(sizeof(GraphRep));
|
||||||
assert(g != NULL);
|
assert(g != NULL);
|
||||||
g->nV = V;
|
g->nV = V;
|
||||||
g->nE = 0;
|
g->nE = 0;
|
||||||
|
|
||||||
// allocate memory for each row
|
// allocate memory for each row
|
||||||
g->edges = malloc(V * sizeof(int *));
|
g->edges = malloc(V * sizeof(int *));
|
||||||
assert(g->edges != NULL);
|
assert(g->edges != NULL);
|
||||||
// allocate memory for each column and initialise with 0
|
// 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);
|
g->edges[i] = calloc(V, sizeof(int));
|
||||||
}
|
assert(g->edges[i] != NULL);
|
||||||
|
}
|
||||||
|
|
||||||
return g;
|
return g;
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if vertex is valid in a graph
|
// check if vertex is valid in a graph
|
||||||
bool validV(Graph g, Vertex v) {
|
bool validV(Graph g, Vertex v) { return (g != NULL && v >= 0 && v < g->nV); }
|
||||||
return (g != NULL && v >= 0 && v < g->nV);
|
|
||||||
|
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
|
||||||
|
g->edges[e.v][e.w] = 1;
|
||||||
|
g->edges[e.w][e.v] = 1;
|
||||||
|
g->nE++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void insertEdge(Graph g, Edge e) {
|
void removeEdge(Graph g, Edge e)
|
||||||
assert(g != NULL && validV(g,e.v) && validV(g,e.w));
|
{
|
||||||
|
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])
|
||||||
g->edges[e.v][e.w] = 1;
|
{ // edge e in graph
|
||||||
g->edges[e.w][e.v] = 1;
|
g->edges[e.v][e.w] = 0;
|
||||||
g->nE++;
|
g->edges[e.w][e.v] = 0;
|
||||||
}
|
g->nE--;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void removeEdge(Graph g, Edge e) {
|
bool adjacent(Graph g, Vertex v, Vertex w)
|
||||||
assert(g != NULL && validV(g,e.v) && validV(g,e.w));
|
{
|
||||||
|
assert(g != NULL && validV(g, v) && validV(g, w));
|
||||||
|
|
||||||
if (g->edges[e.v][e.w]) { // edge e in graph
|
return (g->edges[v][w] != 0);
|
||||||
g->edges[e.v][e.w] = 0;
|
|
||||||
g->edges[e.w][e.v] = 0;
|
|
||||||
g->nE--;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool adjacent(Graph g, Vertex v, Vertex w) {
|
void showGraph(Graph g)
|
||||||
assert(g != NULL && validV(g,v) && validV(g,w));
|
{
|
||||||
|
|
||||||
return (g->edges[v][w] != 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void showGraph(Graph g) {
|
|
||||||
assert(g != NULL);
|
assert(g != NULL);
|
||||||
int i, j;
|
int i, j;
|
||||||
|
|
||||||
printf("Number of vertices: %d\n", g->nV);
|
printf("Number of vertices: %d\n", g->nV);
|
||||||
printf("Number of edges: %d\n", g->nE);
|
printf("Number of edges: %d\n", g->nE);
|
||||||
for (i = 0; i < g->nV; i++)
|
for (i = 0; i < g->nV; i++)
|
||||||
for (j = i+1; j < g->nV; j++)
|
for (j = i + 1; j < g->nV; j++)
|
||||||
if (g->edges[i][j])
|
if (g->edges[i][j])
|
||||||
printf("Edge %d - %d\n", i, j);
|
printf("Edge %d - %d\n", i, j);
|
||||||
}
|
}
|
||||||
|
|
||||||
void freeGraph(Graph g) {
|
void freeGraph(Graph g)
|
||||||
assert(g != NULL);
|
{
|
||||||
|
assert(g != NULL);
|
||||||
|
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < g->nV; i++)
|
for (i = 0; i < g->nV; i++)
|
||||||
free(g->edges[i]);
|
free(g->edges[i]);
|
||||||
free(g->edges);
|
free(g->edges);
|
||||||
free(g);
|
free(g);
|
||||||
}
|
}
|
||||||
|
|
||||||
// By
|
// By
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
// .----------------. .----------------. .----------------.
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
// .-----------------. .----------------. .----------------.
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Graph ADT interface ... COMP2521
|
// Graph ADT interface ... COMP2521
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
|
|
||||||
typedef struct GraphRep *Graph;
|
typedef struct GraphRep *Graph;
|
||||||
@ -7,31 +7,39 @@ typedef struct GraphRep *Graph;
|
|||||||
typedef int Vertex;
|
typedef int Vertex;
|
||||||
|
|
||||||
// edges are pairs of vertices (end-points)
|
// edges are pairs of vertices (end-points)
|
||||||
typedef struct Edge {
|
typedef struct Edge
|
||||||
Vertex v;
|
{
|
||||||
Vertex w;
|
Vertex v;
|
||||||
|
Vertex w;
|
||||||
} Edge;
|
} Edge;
|
||||||
|
|
||||||
Graph newGraph(int);
|
Graph newGraph(int);
|
||||||
void insertEdge(Graph, Edge);
|
void insertEdge(Graph, Edge);
|
||||||
void removeEdge(Graph, Edge);
|
void removeEdge(Graph, Edge);
|
||||||
bool adjacent(Graph, Vertex, Vertex);
|
bool adjacent(Graph, Vertex, Vertex);
|
||||||
void showGraph(Graph);
|
void showGraph(Graph);
|
||||||
void freeGraph(Graph);
|
void freeGraph(Graph);
|
||||||
|
|
||||||
|
// By
|
||||||
|
// .----------------. .----------------. .----------------.
|
||||||
|
// .-----------------. .----------------. .----------------.
|
||||||
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// By
|
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,81 +1,125 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
#include "queue.h"
|
|
||||||
#include "Graph.h"
|
#include "Graph.h"
|
||||||
|
#include "queue.h"
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
#define MAX_NODES 1000
|
#define MAX_NODES 1000
|
||||||
|
|
||||||
int visited[MAX_NODES]; // array to store visiting order
|
int visited[MAX_NODES]; // array to store visiting order
|
||||||
// indexed by vertex 0..nV-1
|
// 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++)
|
Vertex v;
|
||||||
visited[v] = -1;
|
for (v = 0; v < nV; v++)
|
||||||
|
visited[v] = -1;
|
||||||
|
|
||||||
visited[src] = src;
|
visited[src] = src;
|
||||||
queue Q = newQueue();
|
queue Q = newQueue();
|
||||||
QueueEnqueue(Q, src);
|
QueueEnqueue(Q, src);
|
||||||
while (!QueueIsEmpty(Q)) {
|
while (!QueueIsEmpty(Q))
|
||||||
v = QueueDequeue(Q);
|
{
|
||||||
Vertex w;
|
v = QueueDequeue(Q);
|
||||||
for (w = 0; w < nV; w++)
|
Vertex w;
|
||||||
if (adjacent(g, v, w) && visited[w] == -1) {
|
for (w = 0; w < nV; w++)
|
||||||
visited[w] = v;
|
if (adjacent(g, v, w) && visited[w] == -1)
|
||||||
if (w == dest)
|
{
|
||||||
return true;
|
visited[w] = v;
|
||||||
else
|
if (w == dest)
|
||||||
QueueEnqueue(Q, w);
|
return true;
|
||||||
}
|
else
|
||||||
}
|
QueueEnqueue(Q, w);
|
||||||
return false;
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void) {
|
int main(void)
|
||||||
int V = 10;
|
{
|
||||||
Graph g = newGraph(V);
|
int V = 10;
|
||||||
|
Graph g = newGraph(V);
|
||||||
|
|
||||||
Edge e;
|
Edge e;
|
||||||
e.v = 0; e.w = 1; insertEdge(g, e);
|
e.v = 0;
|
||||||
e.v = 0; e.w = 2; insertEdge(g, e);
|
e.w = 1;
|
||||||
e.v = 0; e.w = 5; insertEdge(g, e);
|
insertEdge(g, e);
|
||||||
e.v = 1; e.w = 5; insertEdge(g, e);
|
e.v = 0;
|
||||||
e.v = 2; e.w = 3; insertEdge(g, e);
|
e.w = 2;
|
||||||
e.v = 3; e.w = 4; insertEdge(g, e);
|
insertEdge(g, e);
|
||||||
e.v = 3; e.w = 5; insertEdge(g, e);
|
e.v = 0;
|
||||||
e.v = 3; e.w = 8; insertEdge(g, e);
|
e.w = 5;
|
||||||
e.v = 4; e.w = 5; insertEdge(g, e);
|
insertEdge(g, e);
|
||||||
e.v = 4; e.w = 7; insertEdge(g, e);
|
e.v = 1;
|
||||||
e.v = 4; e.w = 8; insertEdge(g, e);
|
e.w = 5;
|
||||||
e.v = 5; e.w = 6; insertEdge(g, e);
|
insertEdge(g, e);
|
||||||
e.v = 7; e.w = 8; insertEdge(g, e);
|
e.v = 2;
|
||||||
e.v = 7; e.w = 9; insertEdge(g, e);
|
e.w = 3;
|
||||||
e.v = 8; e.w = 9; insertEdge(g, e);
|
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;
|
int src = 0, dest = 6;
|
||||||
if (findPathBFS(g, V, src, dest)) {
|
if (findPathBFS(g, V, src, dest))
|
||||||
Vertex v = dest;
|
{
|
||||||
while (v != src) {
|
Vertex v = dest;
|
||||||
printf("%d - ", v);
|
while (v != src)
|
||||||
v = visited[v];
|
{
|
||||||
}
|
printf("%d - ", v);
|
||||||
printf("%d\n", src);
|
v = visited[v];
|
||||||
}
|
}
|
||||||
return 0;
|
printf("%d\n", src);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// By
|
// By
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
// .----------------. .----------------. .----------------.
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
// .-----------------. .----------------. .----------------.
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,74 +1,104 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
#include "Graph.h"
|
#include "Graph.h"
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
#define MAX_NODES 1000
|
#define MAX_NODES 1000
|
||||||
|
|
||||||
int visited[MAX_NODES]; // array to store visiting order
|
int visited[MAX_NODES]; // array to store visiting order
|
||||||
// indexed by vertex 0..nV-1
|
// 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++)
|
Vertex w;
|
||||||
if (adjacent(g, v, w) && visited[w] == -1) {
|
for (w = 0; w < nV; w++)
|
||||||
visited[w] = v;
|
if (adjacent(g, v, w) && visited[w] == -1)
|
||||||
if (w == dest)
|
{
|
||||||
return true;
|
visited[w] = v;
|
||||||
else if (dfsPathCheck(g, nV, w, dest))
|
if (w == dest)
|
||||||
return true;
|
return true;
|
||||||
}
|
else if (dfsPathCheck(g, nV, w, dest))
|
||||||
return false;
|
return true;
|
||||||
|
}
|
||||||
|
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++)
|
Vertex v;
|
||||||
visited[v] = -1;
|
for (v = 0; v < nV; v++)
|
||||||
visited[src] = src;
|
visited[v] = -1;
|
||||||
return dfsPathCheck(g, nV, src, dest);
|
visited[src] = src;
|
||||||
|
return dfsPathCheck(g, nV, src, dest);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void) {
|
int main(void)
|
||||||
int V = 6;
|
{
|
||||||
Graph g = newGraph(V);
|
int V = 6;
|
||||||
|
Graph g = newGraph(V);
|
||||||
|
|
||||||
Edge e;
|
Edge e;
|
||||||
e.v = 0; e.w = 1; insertEdge(g, e);
|
e.v = 0;
|
||||||
e.v = 0; e.w = 4; insertEdge(g, e);
|
e.w = 1;
|
||||||
e.v = 0; e.w = 5; insertEdge(g, e);
|
insertEdge(g, e);
|
||||||
e.v = 5; e.w = 4; insertEdge(g, e);
|
e.v = 0;
|
||||||
e.v = 4; e.w = 2; insertEdge(g, e);
|
e.w = 4;
|
||||||
e.v = 4; e.w = 3; insertEdge(g, e);
|
insertEdge(g, e);
|
||||||
e.v = 5; e.w = 3; insertEdge(g, e);
|
e.v = 0;
|
||||||
e.v = 1; e.w = 2; insertEdge(g, e);
|
e.w = 5;
|
||||||
e.v = 3; e.w = 2; insertEdge(g, e);
|
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;
|
int src = 0, dest = 5;
|
||||||
if (findPathDFS(g, V, src, dest)) {
|
if (findPathDFS(g, V, src, dest))
|
||||||
Vertex v = dest;
|
{
|
||||||
while (v != src) {
|
Vertex v = dest;
|
||||||
printf("%d - ", v);
|
while (v != src)
|
||||||
v = visited[v];
|
{
|
||||||
}
|
printf("%d - ", v);
|
||||||
printf("%d\n", src);
|
v = visited[v];
|
||||||
}
|
}
|
||||||
return 0;
|
printf("%d\n", src);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// By
|
||||||
|
// .----------------. .----------------. .----------------.
|
||||||
|
// .-----------------. .----------------. .----------------.
|
||||||
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// By
|
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
|
||||||
|
@ -1,82 +1,95 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
#include "Graph.h"
|
#include "Graph.h"
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
// Return the number of vertices that v is
|
// Return the number of vertices that v is
|
||||||
// connected to
|
// connected to
|
||||||
int degree(Graph g, int nV, Vertex v) {
|
int degree(Graph g, int nV, Vertex v)
|
||||||
int deg = 0;
|
{
|
||||||
Vertex w;
|
int deg = 0;
|
||||||
for (w = 0; w < nV; w++)
|
Vertex w;
|
||||||
if (adjacent(g, v, w))
|
for (w = 0; w < nV; w++)
|
||||||
deg++;
|
if (adjacent(g, v, w))
|
||||||
return deg;
|
deg++;
|
||||||
|
return deg;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If start from vertex v, decide if the
|
// If start from vertex v, decide if the
|
||||||
// graph has euler path
|
// graph has euler path
|
||||||
bool hasEulerPath(Graph g, int nV, Vertex v, Vertex 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)
|
if (v != w)
|
||||||
return false;
|
{
|
||||||
} else if (degree(g, nV, v) % 2 != 0) {
|
if (degree(g, nV, v) % 2 == 0 || degree(g, nV, w) % 2 == 0)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Vertex x;
|
else if (degree(g, nV, v) % 2 != 0)
|
||||||
for (x = 0; x < nV; x++)
|
{
|
||||||
if (x != v && x != w && degree(g, nV, x) % 2 != 0)
|
return false;
|
||||||
return false;
|
}
|
||||||
return true;
|
Vertex x;
|
||||||
|
for (x = 0; x < nV; x++)
|
||||||
|
if (x != v && x != w && degree(g, nV, x) % 2 != 0)
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void) {
|
int main(void)
|
||||||
Edge e;
|
{
|
||||||
int n;
|
Edge e;
|
||||||
|
int n;
|
||||||
|
|
||||||
printf("Enter the number of vertices: ");
|
printf("Enter the number of vertices: ");
|
||||||
scanf("%d", &n);
|
scanf("%d", &n);
|
||||||
Graph g = newGraph(n);
|
Graph g = newGraph(n);
|
||||||
|
|
||||||
Vertex src, dest;
|
Vertex src, dest;
|
||||||
printf("Enter source node: ");
|
printf("Enter source node: ");
|
||||||
scanf("%d", &src);
|
scanf("%d", &src);
|
||||||
printf("Enter destination node: ");
|
printf("Enter destination node: ");
|
||||||
scanf("%d", &dest);
|
scanf("%d", &dest);
|
||||||
|
|
||||||
printf("Enter an edge (from): ");
|
|
||||||
while (scanf("%d", &e.v) == 1) {
|
|
||||||
printf("Enter an edge (to): ");
|
|
||||||
scanf("%d", &e.w);
|
|
||||||
insertEdge(g, e);
|
|
||||||
printf("Enter an edge (from): ");
|
|
||||||
}
|
|
||||||
printf("Finished.\n");
|
|
||||||
|
|
||||||
printf("The graph has ");
|
printf("Enter an edge (from): ");
|
||||||
if (hasEulerPath(g, n, src, dest))
|
while (scanf("%d", &e.v) == 1)
|
||||||
printf("an");
|
{
|
||||||
else
|
printf("Enter an edge (to): ");
|
||||||
printf("no");
|
scanf("%d", &e.w);
|
||||||
printf(" Euler path from %d to %d.\n", src, dest);
|
insertEdge(g, e);
|
||||||
|
printf("Enter an edge (from): ");
|
||||||
|
}
|
||||||
|
printf("Finished.\n");
|
||||||
|
|
||||||
freeGraph(g);
|
printf("The graph has ");
|
||||||
return 0;
|
if (hasEulerPath(g, n, src, dest))
|
||||||
|
printf("an");
|
||||||
|
else
|
||||||
|
printf("no");
|
||||||
|
printf(" Euler path from %d to %d.\n", src, dest);
|
||||||
|
|
||||||
|
freeGraph(g);
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// By
|
||||||
|
// .----------------. .----------------. .----------------.
|
||||||
|
// .-----------------. .----------------. .----------------.
|
||||||
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
|
|
||||||
// By
|
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,87 +1,104 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
#include "Graph.h"
|
#include "Graph.h"
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
#define MAX_NODES 1000
|
#define MAX_NODES 1000
|
||||||
|
|
||||||
bool visited[MAX_NODES];
|
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
|
// v = current vertex considered
|
||||||
// d = distance "remaining" until path found
|
// dest = destination vertex
|
||||||
|
// d = distance "remaining" until path found
|
||||||
|
|
||||||
Vertex w;
|
Vertex w;
|
||||||
if (v == dest) {
|
if (v == dest)
|
||||||
return (d == 0);
|
{
|
||||||
} else {
|
return (d == 0);
|
||||||
visited[v] = true;
|
}
|
||||||
for (w = 0; w < nV; w++) {
|
else
|
||||||
if (adjacent(g, v, w) && !visited[w]) {
|
{
|
||||||
if (hamiltonR(g, nV, w, dest, d-1)) {
|
visited[v] = true;
|
||||||
return true;
|
for (w = 0; w < nV; w++)
|
||||||
}
|
{
|
||||||
}
|
if (adjacent(g, v, w) && !visited[w])
|
||||||
}
|
{
|
||||||
}
|
if (hamiltonR(g, nV, w, dest, d - 1))
|
||||||
visited[v] = false;
|
{
|
||||||
return false;
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visited[v] = false;
|
||||||
|
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++)
|
Vertex v;
|
||||||
visited[v] = false;
|
for (v = 0; v < nV; v++)
|
||||||
return hamiltonR(g, nV, src, dest, nV-1);
|
visited[v] = false;
|
||||||
|
return hamiltonR(g, nV, src, dest, nV - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void) {
|
int main(void)
|
||||||
Edge e;
|
{
|
||||||
int n;
|
Edge e;
|
||||||
|
int n;
|
||||||
|
|
||||||
printf("Enter the number of vertices: ");
|
printf("Enter the number of vertices: ");
|
||||||
scanf("%d", &n);
|
scanf("%d", &n);
|
||||||
Graph g = newGraph(n);
|
Graph g = newGraph(n);
|
||||||
|
|
||||||
Vertex src, dest;
|
Vertex src, dest;
|
||||||
printf("Enter source node: ");
|
printf("Enter source node: ");
|
||||||
scanf("%d", &src);
|
scanf("%d", &src);
|
||||||
printf("Enter destination node: ");
|
printf("Enter destination node: ");
|
||||||
scanf("%d", &dest);
|
scanf("%d", &dest);
|
||||||
|
|
||||||
printf("Enter an edge (from): ");
|
|
||||||
while (scanf("%d", &e.v) == 1) {
|
|
||||||
printf("Enter an edge (to): ");
|
|
||||||
scanf("%d", &e.w);
|
|
||||||
insertEdge(g, e);
|
|
||||||
printf("Enter an edge (from): ");
|
|
||||||
}
|
|
||||||
printf("Finished.\n");
|
|
||||||
|
|
||||||
printf("The graph has ");
|
printf("Enter an edge (from): ");
|
||||||
if (hasHamiltonianPath(g, n, src, dest))
|
while (scanf("%d", &e.v) == 1)
|
||||||
printf("a");
|
{
|
||||||
else
|
printf("Enter an edge (to): ");
|
||||||
printf("no");
|
scanf("%d", &e.w);
|
||||||
printf(" Hamiltonian path from %d to %d.\n", src, dest);
|
insertEdge(g, e);
|
||||||
|
printf("Enter an edge (from): ");
|
||||||
|
}
|
||||||
|
printf("Finished.\n");
|
||||||
|
|
||||||
freeGraph(g);
|
printf("The graph has ");
|
||||||
return 0;
|
if (hasHamiltonianPath(g, n, src, dest))
|
||||||
|
printf("a");
|
||||||
|
else
|
||||||
|
printf("no");
|
||||||
|
printf(" Hamiltonian path from %d to %d.\n", src, dest);
|
||||||
|
|
||||||
|
freeGraph(g);
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// By
|
||||||
|
// .----------------. .----------------. .----------------.
|
||||||
|
// .-----------------. .----------------. .----------------.
|
||||||
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// By
|
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,189 +1,187 @@
|
|||||||
// C program for Kruskal's algorithm to find Minimum Spanning Tree
|
// C program for Kruskal's algorithm to find Minimum Spanning Tree
|
||||||
// of a given connected, undirected and weighted graph
|
// of a given connected, undirected and weighted graph
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
// a structure to represent a weighted edge in graph
|
// a structure to represent a weighted edge in graph
|
||||||
struct Edge
|
struct Edge
|
||||||
{
|
{
|
||||||
int src, dest, weight;
|
int src, dest, weight;
|
||||||
};
|
};
|
||||||
|
|
||||||
// a structure to represent a connected, undirected
|
// a structure to represent a connected, undirected
|
||||||
// and weighted graph
|
// and weighted graph
|
||||||
struct Graph
|
struct Graph
|
||||||
{
|
{
|
||||||
// V-> Number of vertices, E-> Number of edges
|
// V-> Number of vertices, E-> Number of edges
|
||||||
int V, E;
|
int V, E;
|
||||||
|
|
||||||
// graph is represented as an array of edges.
|
// graph is represented as an array of edges.
|
||||||
// Since the graph is undirected, the edge
|
// Since the graph is undirected, the edge
|
||||||
// from src to dest is also edge from dest
|
// from src to dest is also edge from dest
|
||||||
// to src. Both are counted as 1 edge here.
|
// to src. Both are counted as 1 edge here.
|
||||||
struct Edge* edge;
|
struct Edge *edge;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Creates a graph with V vertices and E edges
|
// Creates a graph with V vertices and E edges
|
||||||
struct Graph* createGraph(int V, int E)
|
struct Graph *createGraph(int V, int E)
|
||||||
{
|
{
|
||||||
struct Graph* graph = new Graph();
|
struct Graph *graph = new Graph();
|
||||||
graph->V = V;
|
graph->V = V;
|
||||||
graph->E = E;
|
graph->E = E;
|
||||||
|
|
||||||
graph->edge = new Edge[E];
|
graph->edge = new Edge[E];
|
||||||
|
|
||||||
return graph;
|
return graph;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A structure to represent a subset for union-find
|
// A structure to represent a subset for union-find
|
||||||
struct subset
|
struct subset
|
||||||
{
|
{
|
||||||
int parent;
|
int parent;
|
||||||
int rank;
|
int rank;
|
||||||
};
|
};
|
||||||
|
|
||||||
// A utility function to find set of an element i
|
// A utility function to find set of an element i
|
||||||
// (uses path compression technique)
|
// (uses path compression technique)
|
||||||
int find(struct subset subsets[], int i)
|
int find(struct subset subsets[], int i)
|
||||||
{
|
{
|
||||||
// find root and make root as parent of i
|
// find root and make root as parent of i
|
||||||
// (path compression)
|
// (path compression)
|
||||||
if (subsets[i].parent != i)
|
if (subsets[i].parent != i)
|
||||||
subsets[i].parent = find(subsets, subsets[i].parent);
|
subsets[i].parent = find(subsets, subsets[i].parent);
|
||||||
|
|
||||||
return subsets[i].parent;
|
return subsets[i].parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A function that does union of two sets of x and y
|
// A function that does union of two sets of x and y
|
||||||
// (uses union by rank)
|
// (uses union by rank)
|
||||||
void Union(struct subset subsets[], int x, int y)
|
void Union(struct subset subsets[], int x, int y)
|
||||||
{
|
{
|
||||||
int xroot = find(subsets, x);
|
int xroot = find(subsets, x);
|
||||||
int yroot = find(subsets, y);
|
int yroot = find(subsets, y);
|
||||||
|
|
||||||
// Attach smaller rank tree under root of high
|
// Attach smaller rank tree under root of high
|
||||||
// rank tree (Union by Rank)
|
// rank tree (Union by Rank)
|
||||||
if (subsets[xroot].rank < subsets[yroot].rank)
|
if (subsets[xroot].rank < subsets[yroot].rank)
|
||||||
subsets[xroot].parent = yroot;
|
subsets[xroot].parent = yroot;
|
||||||
else if (subsets[xroot].rank > subsets[yroot].rank)
|
else if (subsets[xroot].rank > subsets[yroot].rank)
|
||||||
subsets[yroot].parent = xroot;
|
subsets[yroot].parent = xroot;
|
||||||
|
|
||||||
// If ranks are same, then make one as root and
|
// If ranks are same, then make one as root and
|
||||||
// increment its rank by one
|
// increment its rank by one
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
subsets[yroot].parent = xroot;
|
subsets[yroot].parent = xroot;
|
||||||
subsets[xroot].rank++;
|
subsets[xroot].rank++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compare two edges according to their weights.
|
// Compare two edges according to their weights.
|
||||||
// Used in qsort() for sorting an array of edges
|
// Used in qsort() for sorting an array of edges
|
||||||
int myComp(const void* a, const void* b)
|
int myComp(const void *a, const void *b)
|
||||||
{
|
{
|
||||||
struct Edge* a1 = (struct Edge*)a;
|
struct Edge *a1 = (struct Edge *)a;
|
||||||
struct Edge* b1 = (struct Edge*)b;
|
struct Edge *b1 = (struct Edge *)b;
|
||||||
return a1->weight > b1->weight;
|
return a1->weight > b1->weight;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The main function to construct MST using Kruskal's algorithm
|
// The main function to construct MST using Kruskal's algorithm
|
||||||
void KruskalMST(struct Graph* graph)
|
void KruskalMST(struct Graph *graph)
|
||||||
{
|
{
|
||||||
int V = graph->V;
|
int V = graph->V;
|
||||||
struct Edge result[V]; // Tnis will store the resultant MST
|
struct Edge result[V]; // Tnis will store the resultant MST
|
||||||
int e = 0; // An index variable, used for result[]
|
int e = 0; // An index variable, used for result[]
|
||||||
int i = 0; // An index variable, used for sorted edges
|
int i = 0; // An index variable, used for sorted edges
|
||||||
|
|
||||||
// Step 1: Sort all the edges in non-decreasing
|
// Step 1: Sort all the edges in non-decreasing
|
||||||
// order of their weight. If we are not allowed to
|
// order of their weight. If we are not allowed to
|
||||||
// change the given graph, we can create a copy of
|
// change the given graph, we can create a copy of
|
||||||
// array of edges
|
// array of edges
|
||||||
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
|
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
|
||||||
|
|
||||||
// Allocate memory for creating V ssubsets
|
// Allocate memory for creating V ssubsets
|
||||||
struct subset *subsets =
|
struct subset *subsets = (struct subset *)malloc(V * sizeof(struct subset));
|
||||||
(struct subset*) malloc( V * sizeof(struct subset) );
|
|
||||||
|
|
||||||
// Create V subsets with single elements
|
// Create V subsets with single elements
|
||||||
for (int v = 0; v < V; ++v)
|
for (int v = 0; v < V; ++v)
|
||||||
{
|
{
|
||||||
subsets[v].parent = v;
|
subsets[v].parent = v;
|
||||||
subsets[v].rank = 0;
|
subsets[v].rank = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Number of edges to be taken is equal to V-1
|
// Number of edges to be taken is equal to V-1
|
||||||
while (e < V - 1 && i < graph->E)
|
while (e < V - 1 && i < graph->E)
|
||||||
{
|
{
|
||||||
// Step 2: Pick the smallest edge. And increment
|
// Step 2: Pick the smallest edge. And increment
|
||||||
// the index for next iteration
|
// the index for next iteration
|
||||||
struct Edge next_edge = graph->edge[i++];
|
struct Edge next_edge = graph->edge[i++];
|
||||||
|
|
||||||
int x = find(subsets, next_edge.src);
|
int x = find(subsets, next_edge.src);
|
||||||
int y = find(subsets, next_edge.dest);
|
int y = find(subsets, next_edge.dest);
|
||||||
|
|
||||||
// If including this edge does't cause cycle,
|
// If including this edge does't cause cycle,
|
||||||
// include it in result and increment the index
|
// include it in result and increment the index
|
||||||
// of result for next edge
|
// of result for next edge
|
||||||
if (x != y)
|
if (x != y)
|
||||||
{
|
{
|
||||||
result[e++] = next_edge;
|
result[e++] = next_edge;
|
||||||
Union(subsets, x, y);
|
Union(subsets, x, y);
|
||||||
}
|
}
|
||||||
// Else discard the next_edge
|
// Else discard the next_edge
|
||||||
}
|
}
|
||||||
|
|
||||||
// print the contents of result[] to display the
|
// print the contents of result[] to display the
|
||||||
// built MST
|
// built MST
|
||||||
printf("Following are the edges in the constructed MST\n");
|
printf("Following are the edges in the constructed MST\n");
|
||||||
for (i = 0; i < e; ++i)
|
for (i = 0; i < e; ++i)
|
||||||
printf("%d -- %d == %d\n", result[i].src, result[i].dest,
|
printf("%d -- %d == %d\n", result[i].src, result[i].dest,
|
||||||
result[i].weight);
|
result[i].weight);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Driver program to test above functions
|
// Driver program to test above functions
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
/* Let us create following weighted graph
|
/* Let us create following weighted graph
|
||||||
10
|
10
|
||||||
0--------1
|
0--------1
|
||||||
| \ |
|
| \ |
|
||||||
6| 5\ |15
|
6| 5\ |15
|
||||||
| \ |
|
| \ |
|
||||||
2--------3
|
2--------3
|
||||||
4 */
|
4 */
|
||||||
int V = 4; // Number of vertices in graph
|
int V = 4; // Number of vertices in graph
|
||||||
int E = 5; // Number of edges in graph
|
int E = 5; // Number of edges in graph
|
||||||
struct Graph* graph = createGraph(V, E);
|
struct Graph *graph = createGraph(V, E);
|
||||||
|
|
||||||
|
// add edge 0-1
|
||||||
|
graph->edge[0].src = 0;
|
||||||
|
graph->edge[0].dest = 1;
|
||||||
|
graph->edge[0].weight = 10;
|
||||||
|
|
||||||
// add edge 0-1
|
// add edge 0-2
|
||||||
graph->edge[0].src = 0;
|
graph->edge[1].src = 0;
|
||||||
graph->edge[0].dest = 1;
|
graph->edge[1].dest = 2;
|
||||||
graph->edge[0].weight = 10;
|
graph->edge[1].weight = 6;
|
||||||
|
|
||||||
// add edge 0-2
|
// add edge 0-3
|
||||||
graph->edge[1].src = 0;
|
graph->edge[2].src = 0;
|
||||||
graph->edge[1].dest = 2;
|
graph->edge[2].dest = 3;
|
||||||
graph->edge[1].weight = 6;
|
graph->edge[2].weight = 5;
|
||||||
|
|
||||||
// add edge 0-3
|
// add edge 1-3
|
||||||
graph->edge[2].src = 0;
|
graph->edge[3].src = 1;
|
||||||
graph->edge[2].dest = 3;
|
graph->edge[3].dest = 3;
|
||||||
graph->edge[2].weight = 5;
|
graph->edge[3].weight = 15;
|
||||||
|
|
||||||
// add edge 1-3
|
// add edge 2-3
|
||||||
graph->edge[3].src = 1;
|
graph->edge[4].src = 2;
|
||||||
graph->edge[3].dest = 3;
|
graph->edge[4].dest = 3;
|
||||||
graph->edge[3].weight = 15;
|
graph->edge[4].weight = 4;
|
||||||
|
|
||||||
// add edge 2-3
|
KruskalMST(graph);
|
||||||
graph->edge[4].src = 2;
|
|
||||||
graph->edge[4].dest = 3;
|
|
||||||
graph->edge[4].weight = 4;
|
|
||||||
|
|
||||||
KruskalMST(graph);
|
return 0;
|
||||||
|
}
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
@ -1,88 +1,104 @@
|
|||||||
// Queue ADT implementation ... COMP2521
|
// Queue ADT implementation ... COMP2521
|
||||||
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <assert.h>
|
|
||||||
#include "queue.h"
|
#include "queue.h"
|
||||||
|
#include <assert.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
typedef struct node {
|
typedef struct node
|
||||||
int data;
|
{
|
||||||
struct node *next;
|
int data;
|
||||||
|
struct node *next;
|
||||||
} NodeT;
|
} NodeT;
|
||||||
|
|
||||||
typedef struct QueueRep {
|
typedef struct QueueRep
|
||||||
int length;
|
{
|
||||||
NodeT *head;
|
int length;
|
||||||
NodeT *tail;
|
NodeT *head;
|
||||||
|
NodeT *tail;
|
||||||
} QueueRep;
|
} QueueRep;
|
||||||
|
|
||||||
// set up empty queue
|
// set up empty queue
|
||||||
queue newQueue() {
|
queue newQueue()
|
||||||
queue Q = malloc(sizeof(QueueRep));
|
{
|
||||||
Q->length = 0;
|
queue Q = malloc(sizeof(QueueRep));
|
||||||
Q->head = NULL;
|
Q->length = 0;
|
||||||
Q->tail = NULL;
|
Q->head = NULL;
|
||||||
return Q;
|
Q->tail = NULL;
|
||||||
|
return Q;
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove unwanted queue
|
// remove unwanted queue
|
||||||
void dropQueue(queue Q) {
|
void dropQueue(queue Q)
|
||||||
NodeT *curr = Q->head;
|
{
|
||||||
while (curr != NULL) {
|
NodeT *curr = Q->head;
|
||||||
NodeT *temp = curr->next;
|
while (curr != NULL)
|
||||||
free(curr);
|
{
|
||||||
curr = temp;
|
NodeT *temp = curr->next;
|
||||||
}
|
free(curr);
|
||||||
free(Q);
|
curr = temp;
|
||||||
|
}
|
||||||
|
free(Q);
|
||||||
}
|
}
|
||||||
|
|
||||||
// check whether queue is empty
|
// check whether queue is empty
|
||||||
int QueueIsEmpty(queue Q) {
|
int QueueIsEmpty(queue Q) { return (Q->length == 0); }
|
||||||
return (Q->length == 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// insert an int at end of queue
|
// 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);
|
NodeT *new = malloc(sizeof(NodeT));
|
||||||
new->data = v;
|
assert(new != NULL);
|
||||||
new->next = NULL;
|
new->data = v;
|
||||||
if (Q->tail != NULL) {
|
new->next = NULL;
|
||||||
Q->tail->next = new;
|
if (Q->tail != NULL)
|
||||||
Q->tail = new;
|
{
|
||||||
} else {
|
Q->tail->next = new;
|
||||||
Q->head = new;
|
Q->tail = new;
|
||||||
Q->tail = new;
|
}
|
||||||
}
|
else
|
||||||
Q->length++;
|
{
|
||||||
|
Q->head = new;
|
||||||
|
Q->tail = new;
|
||||||
|
}
|
||||||
|
Q->length++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove int from front of queue
|
// remove int from front of queue
|
||||||
int QueueDequeue(queue Q) {
|
int QueueDequeue(queue Q)
|
||||||
assert(Q->length > 0);
|
{
|
||||||
NodeT *p = Q->head;
|
assert(Q->length > 0);
|
||||||
Q->head = Q->head->next;
|
NodeT *p = Q->head;
|
||||||
if (Q->head == NULL) {
|
Q->head = Q->head->next;
|
||||||
Q->tail = NULL;
|
if (Q->head == NULL)
|
||||||
}
|
{
|
||||||
Q->length--;
|
Q->tail = NULL;
|
||||||
int d = p->data;
|
}
|
||||||
free(p);
|
Q->length--;
|
||||||
return d;
|
int d = p->data;
|
||||||
|
free(p);
|
||||||
|
return d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// By
|
||||||
|
// .----------------. .----------------. .----------------.
|
||||||
|
// .-----------------. .----------------. .----------------.
|
||||||
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// By
|
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,26 +1,33 @@
|
|||||||
// Queue ADT header file ... COMP2521
|
// Queue ADT header file ... COMP2521
|
||||||
|
|
||||||
typedef struct QueueRep *queue;
|
typedef struct QueueRep *queue;
|
||||||
|
|
||||||
queue newQueue(); // set up empty queue
|
queue newQueue(); // set up empty queue
|
||||||
void dropQueue(queue); // remove unwanted queue
|
void dropQueue(queue); // remove unwanted queue
|
||||||
int QueueIsEmpty(queue); // check whether queue is empty
|
int QueueIsEmpty(queue); // check whether queue is empty
|
||||||
void QueueEnqueue(queue, int); // insert an int at end of queue
|
void QueueEnqueue(queue, int); // insert an int at end of queue
|
||||||
int QueueDequeue(queue); // remove int from front of queue
|
int QueueDequeue(queue); // remove int from front of queue
|
||||||
|
|
||||||
|
// By
|
||||||
|
// .----------------. .----------------. .----------------.
|
||||||
|
// .-----------------. .----------------. .----------------.
|
||||||
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// By
|
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// hhoanhtuann@gmail.com
|
||||||
|
@ -1,59 +1,61 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#define MAX_SIZE 40//Assume 40 nodes at max in graph
|
#define MAX_SIZE 40 // Assume 40 nodes at max in graph
|
||||||
#define INT_MIN 0
|
#define INT_MIN 0
|
||||||
//A vertex of the graph
|
// A vertex of the graph
|
||||||
struct node
|
struct node
|
||||||
{
|
{
|
||||||
int vertex;
|
int vertex;
|
||||||
struct node* next;
|
struct node *next;
|
||||||
};
|
};
|
||||||
//Some declarations
|
// Some declarations
|
||||||
struct node* createNode(int v);
|
struct node *createNode(int v);
|
||||||
struct Graph
|
struct Graph
|
||||||
{
|
{
|
||||||
int numVertices;
|
int numVertices;
|
||||||
int* visited;
|
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
|
// Structure to create a stack, necessary for topological sorting
|
||||||
struct Stack
|
struct Stack
|
||||||
{
|
{
|
||||||
int arr[MAX_SIZE];
|
int arr[MAX_SIZE];
|
||||||
int top;
|
int top;
|
||||||
};
|
};
|
||||||
struct Graph* createGraph(int);
|
struct Graph *createGraph(int);
|
||||||
void addEdge(struct Graph*, int, int);
|
void addEdge(struct Graph *, int, int);
|
||||||
void printGraph(struct Graph*);
|
void printGraph(struct Graph *);
|
||||||
struct Graph* transpose(struct Graph*);
|
struct Graph *transpose(struct Graph *);
|
||||||
void fillOrder(int,struct Graph*, struct Stack*);
|
void fillOrder(int, struct Graph *, struct Stack *);
|
||||||
void scc(struct Graph*);
|
void scc(struct Graph *);
|
||||||
void dfs(struct Graph*, int);
|
void dfs(struct Graph *, int);
|
||||||
struct Stack* createStack();
|
struct Stack *createStack();
|
||||||
void push(struct Stack*, int);
|
void push(struct Stack *, int);
|
||||||
int pop(struct Stack*);
|
int pop(struct Stack *);
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int vertices,edges,i,src,dst;
|
int vertices, edges, i, src, dst;
|
||||||
printf("Enter the number of vertices\n");
|
printf("Enter the number of vertices\n");
|
||||||
scanf("%d",&vertices);
|
scanf("%d", &vertices);
|
||||||
struct Graph* graph = createGraph(vertices);
|
struct Graph *graph = createGraph(vertices);
|
||||||
printf("Enter the number of edges\n");
|
printf("Enter the number of edges\n");
|
||||||
scanf("%d",&edges);
|
scanf("%d", &edges);
|
||||||
for(i=0; i<edges; i++)
|
for (i = 0; i < edges; i++)
|
||||||
{
|
{
|
||||||
printf("Edge %d \nEnter source: ",i+1);
|
printf("Edge %d \nEnter source: ", i + 1);
|
||||||
scanf("%d",&src);
|
scanf("%d", &src);
|
||||||
printf("Enter destination: ");
|
printf("Enter destination: ");
|
||||||
scanf("%d",&dst);
|
scanf("%d", &dst);
|
||||||
addEdge(graph, src, dst);
|
addEdge(graph, src, dst);
|
||||||
}
|
}
|
||||||
printf("The strongly connected conponents are:\n");
|
printf("The strongly connected conponents are:\n");
|
||||||
scc(graph);
|
scc(graph);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
|
|
||||||
//Uncomment below part to get a ready-made example
|
// Uncomment below part to get a ready-made example
|
||||||
/*struct Graph* graph2 = createGraph(4);
|
/*struct Graph* graph2 = createGraph(4);
|
||||||
addEdge(graph2, 0, 1);
|
addEdge(graph2, 0, 1);
|
||||||
addEdge(graph2, 1, 2);
|
addEdge(graph2, 1, 2);
|
||||||
@ -61,127 +63,134 @@ int main()
|
|||||||
addEdge(graph2, 2, 3);
|
addEdge(graph2, 2, 3);
|
||||||
printf("The strongly connected components are:\n");
|
printf("The strongly connected components are:\n");
|
||||||
scc(graph2);
|
scc(graph2);
|
||||||
printf("\n");*/
|
printf("\n");*/
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
//Creates a topological sorting of the graph
|
// Creates a topological sorting of the graph
|
||||||
void fillOrder(int vertex, struct Graph* graph, struct Stack* stack)
|
void fillOrder(int vertex, struct Graph *graph, struct Stack *stack)
|
||||||
{
|
{
|
||||||
graph->visited[vertex]=1;
|
|
||||||
struct node* adjList = graph->adjLists[vertex];
|
|
||||||
struct node* temp = adjList;
|
|
||||||
//First add all dependents (that is, children) to stack
|
|
||||||
while(temp!=NULL) {
|
|
||||||
int connectedVertex = temp->vertex;
|
|
||||||
if(graph->visited[connectedVertex] == 0) {
|
|
||||||
fillOrder(connectedVertex, graph, stack);
|
|
||||||
}
|
|
||||||
temp=temp->next;
|
|
||||||
}
|
|
||||||
//and then add itself
|
|
||||||
push(stack,vertex);
|
|
||||||
}
|
|
||||||
//Transpose the adjacency list
|
|
||||||
struct Graph* transpose(struct Graph* g)
|
|
||||||
{
|
|
||||||
struct Graph* graph = createGraph(g->numVertices);//Number of vertices is same
|
|
||||||
int i=0;
|
|
||||||
for(i=0;i<g->numVertices;i++)
|
|
||||||
{
|
|
||||||
struct node* temp=g->adjLists[i];
|
|
||||||
while(temp!=NULL)
|
|
||||||
{
|
|
||||||
addEdge(graph,temp->vertex,i);//Reverse all edges
|
|
||||||
temp=temp->next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return graph;
|
|
||||||
}
|
|
||||||
//Recursive dfs aproach
|
|
||||||
void dfs(struct Graph* graph, int vertex) {
|
|
||||||
struct node* adjList = graph->adjLists[vertex];
|
|
||||||
struct node* temp = adjList;
|
|
||||||
|
|
||||||
//Add vertex to visited list and print it
|
|
||||||
graph->visited[vertex] = 1;
|
graph->visited[vertex] = 1;
|
||||||
printf("%d ", vertex);
|
struct node *adjList = graph->adjLists[vertex];
|
||||||
|
struct node *temp = adjList;
|
||||||
//Recursively call the dfs function on all unvisited neighbours
|
// First add all dependents (that is, children) to stack
|
||||||
while(temp!=NULL) {
|
while (temp != NULL)
|
||||||
|
{
|
||||||
int connectedVertex = temp->vertex;
|
int connectedVertex = temp->vertex;
|
||||||
if(graph->visited[connectedVertex] == 0) {
|
if (graph->visited[connectedVertex] == 0)
|
||||||
dfs(graph, connectedVertex);
|
{
|
||||||
|
fillOrder(connectedVertex, graph, stack);
|
||||||
}
|
}
|
||||||
temp = temp->next;
|
temp = temp->next;
|
||||||
}
|
}
|
||||||
|
// and then add itself
|
||||||
|
push(stack, vertex);
|
||||||
|
}
|
||||||
|
// Transpose the adjacency list
|
||||||
|
struct Graph *transpose(struct Graph *g)
|
||||||
|
{
|
||||||
|
struct Graph *graph =
|
||||||
|
createGraph(g->numVertices); // Number of vertices is same
|
||||||
|
int i = 0;
|
||||||
|
for (i = 0; i < g->numVertices; i++)
|
||||||
|
{
|
||||||
|
struct node *temp = g->adjLists[i];
|
||||||
|
while (temp != NULL)
|
||||||
|
{
|
||||||
|
addEdge(graph, temp->vertex, i); // Reverse all edges
|
||||||
|
temp = temp->next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return graph;
|
||||||
|
}
|
||||||
|
// Recursive dfs aproach
|
||||||
|
void dfs(struct Graph *graph, int vertex)
|
||||||
|
{
|
||||||
|
struct node *adjList = graph->adjLists[vertex];
|
||||||
|
struct node *temp = adjList;
|
||||||
|
|
||||||
|
// Add vertex to visited list and print it
|
||||||
|
graph->visited[vertex] = 1;
|
||||||
|
printf("%d ", vertex);
|
||||||
|
|
||||||
|
// Recursively call the dfs function on all unvisited neighbours
|
||||||
|
while (temp != NULL)
|
||||||
|
{
|
||||||
|
int connectedVertex = temp->vertex;
|
||||||
|
if (graph->visited[connectedVertex] == 0)
|
||||||
|
{
|
||||||
|
dfs(graph, connectedVertex);
|
||||||
|
}
|
||||||
|
temp = temp->next;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Strongly connected components
|
// Strongly connected components
|
||||||
void scc(struct Graph* graph)
|
void scc(struct Graph *graph)
|
||||||
{
|
{
|
||||||
//Step I: Create a topological sort of the graph and store it in a stack
|
// Step I: Create a topological sort of the graph and store it in a stack
|
||||||
struct Stack* stack=createStack();
|
struct Stack *stack = createStack();
|
||||||
int i=0;
|
int i = 0;
|
||||||
for(i=0;i<graph->numVertices;i++)
|
for (i = 0; i < graph->numVertices; i++)
|
||||||
{
|
{
|
||||||
//Execute topological sort on all elements
|
// Execute topological sort on all elements
|
||||||
if(graph->visited[i]==0)
|
if (graph->visited[i] == 0)
|
||||||
{
|
{
|
||||||
fillOrder(i,graph,stack);
|
fillOrder(i, graph, stack);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Step 2: Get the transpose graph
|
// Step 2: Get the transpose graph
|
||||||
struct Graph* graphT=transpose(graph);
|
struct Graph *graphT = transpose(graph);
|
||||||
//Step 3: Perform a simple dfs by popping nodes from stack
|
// Step 3: Perform a simple dfs by popping nodes from stack
|
||||||
while(stack->top!=-1)
|
while (stack->top != -1)
|
||||||
{
|
{
|
||||||
int v=pop(stack);
|
int v = pop(stack);
|
||||||
if(graphT->visited[v]==0)
|
if (graphT->visited[v] == 0)
|
||||||
{
|
{
|
||||||
dfs(graphT,v);
|
dfs(graphT, v);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Allocate memory for a node
|
// Allocate memory for a node
|
||||||
struct node* createNode(int v)
|
struct node *createNode(int v)
|
||||||
{
|
{
|
||||||
struct node* newNode = malloc(sizeof(struct node));
|
struct node *newNode = malloc(sizeof(struct node));
|
||||||
newNode->vertex = v;
|
newNode->vertex = v;
|
||||||
newNode->next = NULL;
|
newNode->next = NULL;
|
||||||
return newNode;
|
return newNode;
|
||||||
}
|
}
|
||||||
//Allocate memory for the entire graph structure
|
// Allocate memory for the entire graph structure
|
||||||
struct Graph* createGraph(int vertices)
|
struct Graph *createGraph(int vertices)
|
||||||
{
|
{
|
||||||
struct Graph* graph = malloc(sizeof(struct Graph));
|
struct Graph *graph = malloc(sizeof(struct Graph));
|
||||||
graph->numVertices = vertices;
|
graph->numVertices = vertices;
|
||||||
graph->adjLists = malloc(vertices * sizeof(struct node*));
|
graph->adjLists = malloc(vertices * sizeof(struct node *));
|
||||||
graph->visited = malloc(vertices * sizeof(int));
|
graph->visited = malloc(vertices * sizeof(int));
|
||||||
|
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < vertices; i++) {
|
for (i = 0; i < vertices; i++)
|
||||||
|
{
|
||||||
graph->adjLists[i] = NULL;
|
graph->adjLists[i] = NULL;
|
||||||
graph->visited[i] = 0;
|
graph->visited[i] = 0;
|
||||||
}
|
}
|
||||||
return graph;
|
return graph;
|
||||||
}
|
}
|
||||||
//Creates a unidirectional graph
|
// Creates a unidirectional graph
|
||||||
void addEdge(struct Graph* graph, int src, int dest)
|
void addEdge(struct Graph *graph, int src, int dest)
|
||||||
{
|
{
|
||||||
// Add edge from src to dest
|
// Add edge from src to dest
|
||||||
struct node* newNode = createNode(dest);
|
struct node *newNode = createNode(dest);
|
||||||
newNode->next = graph->adjLists[src];
|
newNode->next = graph->adjLists[src];
|
||||||
graph->adjLists[src] = newNode;
|
graph->adjLists[src] = newNode;
|
||||||
}
|
}
|
||||||
//Utility function to see state of graph at a given time
|
// Utility function to see state of graph at a given time
|
||||||
void printGraph(struct Graph* graph)
|
void printGraph(struct Graph *graph)
|
||||||
{
|
{
|
||||||
int v;
|
int v;
|
||||||
for (v = 0; v < graph->numVertices; v++)
|
for (v = 0; v < graph->numVertices; v++)
|
||||||
{
|
{
|
||||||
struct node* temp = graph->adjLists[v];
|
struct node *temp = graph->adjLists[v];
|
||||||
printf("\n Adjacency list of vertex %d\n ", v);
|
printf("\n Adjacency list of vertex %d\n ", v);
|
||||||
while (temp)
|
while (temp)
|
||||||
{
|
{
|
||||||
@ -191,23 +200,24 @@ void printGraph(struct Graph* graph)
|
|||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Creates a stack
|
// Creates a stack
|
||||||
struct Stack* createStack()
|
struct Stack *createStack()
|
||||||
{
|
{
|
||||||
struct Stack* stack=malloc(sizeof(struct Stack));
|
struct Stack *stack = malloc(sizeof(struct Stack));
|
||||||
stack->top=-1;
|
stack->top = -1;
|
||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
//Pushes element into stack
|
// Pushes element into stack
|
||||||
void push(struct Stack* stack,int element)
|
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
|
// Removes element from stack, or returns INT_MIN if stack empty
|
||||||
int pop(struct Stack* stack)
|
int pop(struct Stack *stack)
|
||||||
{
|
{
|
||||||
if(stack->top==-1)
|
if (stack->top == -1)
|
||||||
return INT_MIN;
|
return INT_MIN;
|
||||||
else
|
else
|
||||||
return stack->arr[stack->top--];
|
return stack->arr[stack->top--];
|
||||||
}
|
}
|
||||||
|
@ -1,57 +1,59 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#define MAX_SIZE 40//Assume 40 nodes at max in graph
|
#define MAX_SIZE 40 // Assume 40 nodes at max in graph
|
||||||
#define INT_MIN 0
|
#define INT_MIN 0
|
||||||
//A vertex of the graph
|
// A vertex of the graph
|
||||||
struct node
|
struct node
|
||||||
{
|
{
|
||||||
int vertex;
|
int vertex;
|
||||||
struct node* next;
|
struct node *next;
|
||||||
};
|
};
|
||||||
//Some declarations
|
// Some declarations
|
||||||
struct node* createNode(int v);
|
struct node *createNode(int v);
|
||||||
struct Graph
|
struct Graph
|
||||||
{
|
{
|
||||||
int numVertices;
|
int numVertices;
|
||||||
int* visited;
|
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
|
// Structure to create a stack, necessary for topological sorting
|
||||||
struct Stack
|
struct Stack
|
||||||
{
|
{
|
||||||
int arr[MAX_SIZE];
|
int arr[MAX_SIZE];
|
||||||
int top;
|
int top;
|
||||||
};
|
};
|
||||||
struct Graph* createGraph(int);
|
struct Graph *createGraph(int);
|
||||||
void addEdge(struct Graph*, int, int);
|
void addEdge(struct Graph *, int, int);
|
||||||
void printGraph(struct Graph*);
|
void printGraph(struct Graph *);
|
||||||
void topologicalSortHelper(int,struct Graph*, struct Stack*);
|
void topologicalSortHelper(int, struct Graph *, struct Stack *);
|
||||||
void topologicalSort(struct Graph*);
|
void topologicalSort(struct Graph *);
|
||||||
struct Stack* createStack();
|
struct Stack *createStack();
|
||||||
void push(struct Stack*, int);
|
void push(struct Stack *, int);
|
||||||
int pop(struct Stack*);
|
int pop(struct Stack *);
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int vertices,edges,i,src,dst;
|
int vertices, edges, i, src, dst;
|
||||||
printf("Enter the number of vertices\n");
|
printf("Enter the number of vertices\n");
|
||||||
scanf("%d",&vertices);
|
scanf("%d", &vertices);
|
||||||
struct Graph* graph = createGraph(vertices);
|
struct Graph *graph = createGraph(vertices);
|
||||||
printf("Enter the number of edges\n");
|
printf("Enter the number of edges\n");
|
||||||
scanf("%d",&edges);
|
scanf("%d", &edges);
|
||||||
for(i=0; i<edges; i++)
|
for (i = 0; i < edges; i++)
|
||||||
{
|
{
|
||||||
printf("Edge %d \nEnter source: ",i+1);
|
printf("Edge %d \nEnter source: ", i + 1);
|
||||||
scanf("%d",&src);
|
scanf("%d", &src);
|
||||||
printf("Enter destination: ");
|
printf("Enter destination: ");
|
||||||
scanf("%d",&dst);
|
scanf("%d", &dst);
|
||||||
addEdge(graph, src, dst);
|
addEdge(graph, src, dst);
|
||||||
}
|
}
|
||||||
printf("One topological sort order is:\n");
|
printf("One topological sort order is:\n");
|
||||||
topologicalSort(graph);
|
topologicalSort(graph);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
|
|
||||||
//Uncomment below part to get a ready-made example
|
// Uncomment below part to get a ready-made example
|
||||||
/*struct Graph* graph2 = createGraph(4);
|
/*struct Graph* graph2 = createGraph(4);
|
||||||
addEdge(graph2, 0, 1);
|
addEdge(graph2, 0, 1);
|
||||||
addEdge(graph2, 0, 2);
|
addEdge(graph2, 0, 2);
|
||||||
@ -59,81 +61,84 @@ int main()
|
|||||||
addEdge(graph2, 2, 3);
|
addEdge(graph2, 2, 3);
|
||||||
printf("One topological sort is:\n");
|
printf("One topological sort is:\n");
|
||||||
topologicalSort(graph2);
|
topologicalSort(graph2);
|
||||||
printf("\n");*/
|
printf("\n");*/
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
void topologicalSortHelper(int vertex, struct Graph* graph, struct Stack* stack)
|
void topologicalSortHelper(int vertex, struct Graph *graph, struct Stack *stack)
|
||||||
{
|
{
|
||||||
graph->visited[vertex]=1;
|
graph->visited[vertex] = 1;
|
||||||
struct node* adjList = graph->adjLists[vertex];
|
struct node *adjList = graph->adjLists[vertex];
|
||||||
struct node* temp = adjList;
|
struct node *temp = adjList;
|
||||||
//First add all dependents (that is, children) to stack
|
// First add all dependents (that is, children) to stack
|
||||||
while(temp!=NULL) {
|
while (temp != NULL)
|
||||||
|
{
|
||||||
int connectedVertex = temp->vertex;
|
int connectedVertex = temp->vertex;
|
||||||
if(graph->visited[connectedVertex] == 0) {
|
if (graph->visited[connectedVertex] == 0)
|
||||||
topologicalSortHelper(connectedVertex, graph, stack);
|
{
|
||||||
}
|
topologicalSortHelper(connectedVertex, graph, stack);
|
||||||
temp=temp->next;
|
}
|
||||||
|
temp = temp->next;
|
||||||
}
|
}
|
||||||
//and then add itself
|
// and then add itself
|
||||||
push(stack,vertex);
|
push(stack, vertex);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Recursive topologial sort approach
|
// Recursive topologial sort approach
|
||||||
void topologicalSort(struct Graph* graph)
|
void topologicalSort(struct Graph *graph)
|
||||||
{
|
{
|
||||||
struct Stack* stack=createStack();
|
struct Stack *stack = createStack();
|
||||||
int i=0;
|
int i = 0;
|
||||||
for(i=0;i<graph->numVertices;i++)
|
for (i = 0; i < graph->numVertices; i++)
|
||||||
{
|
{
|
||||||
//Execute topological sort on all elements
|
// Execute topological sort on all elements
|
||||||
if(graph->visited[i]==0)
|
if (graph->visited[i] == 0)
|
||||||
{
|
{
|
||||||
topologicalSortHelper(i,graph,stack);
|
topologicalSortHelper(i, graph, stack);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
while(stack->top!=-1)
|
while (stack->top != -1)
|
||||||
printf("%d ",pop(stack));
|
printf("%d ", pop(stack));
|
||||||
}
|
}
|
||||||
//Allocate memory for a node
|
// Allocate memory for a node
|
||||||
struct node* createNode(int v)
|
struct node *createNode(int v)
|
||||||
{
|
{
|
||||||
struct node* newNode = malloc(sizeof(struct node));
|
struct node *newNode = malloc(sizeof(struct node));
|
||||||
newNode->vertex = v;
|
newNode->vertex = v;
|
||||||
newNode->next = NULL;
|
newNode->next = NULL;
|
||||||
return newNode;
|
return newNode;
|
||||||
}
|
}
|
||||||
//Allocate memory for the entire graph structure
|
// Allocate memory for the entire graph structure
|
||||||
struct Graph* createGraph(int vertices)
|
struct Graph *createGraph(int vertices)
|
||||||
{
|
{
|
||||||
struct Graph* graph = malloc(sizeof(struct Graph));
|
struct Graph *graph = malloc(sizeof(struct Graph));
|
||||||
graph->numVertices = vertices;
|
graph->numVertices = vertices;
|
||||||
graph->adjLists = malloc(vertices * sizeof(struct node*));
|
graph->adjLists = malloc(vertices * sizeof(struct node *));
|
||||||
graph->visited = malloc(vertices * sizeof(int));
|
graph->visited = malloc(vertices * sizeof(int));
|
||||||
|
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < vertices; i++) {
|
for (i = 0; i < vertices; i++)
|
||||||
|
{
|
||||||
graph->adjLists[i] = NULL;
|
graph->adjLists[i] = NULL;
|
||||||
graph->visited[i] = 0;
|
graph->visited[i] = 0;
|
||||||
}
|
}
|
||||||
return graph;
|
return graph;
|
||||||
}
|
}
|
||||||
//Creates a unidirectional graph
|
// Creates a unidirectional graph
|
||||||
void addEdge(struct Graph* graph, int src, int dest)
|
void addEdge(struct Graph *graph, int src, int dest)
|
||||||
{
|
{
|
||||||
// Add edge from src to dest
|
// Add edge from src to dest
|
||||||
struct node* newNode = createNode(dest);
|
struct node *newNode = createNode(dest);
|
||||||
newNode->next = graph->adjLists[src];
|
newNode->next = graph->adjLists[src];
|
||||||
graph->adjLists[src] = newNode;
|
graph->adjLists[src] = newNode;
|
||||||
}
|
}
|
||||||
//Utility function to see state of graph at a given time
|
// Utility function to see state of graph at a given time
|
||||||
void printGraph(struct Graph* graph)
|
void printGraph(struct Graph *graph)
|
||||||
{
|
{
|
||||||
int v;
|
int v;
|
||||||
for (v = 0; v < graph->numVertices; v++)
|
for (v = 0; v < graph->numVertices; v++)
|
||||||
{
|
{
|
||||||
struct node* temp = graph->adjLists[v];
|
struct node *temp = graph->adjLists[v];
|
||||||
printf("\n Adjacency list of vertex %d\n ", v);
|
printf("\n Adjacency list of vertex %d\n ", v);
|
||||||
while (temp)
|
while (temp)
|
||||||
{
|
{
|
||||||
@ -143,24 +148,24 @@ void printGraph(struct Graph* graph)
|
|||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Creates a stack
|
// Creates a stack
|
||||||
struct Stack* createStack()
|
struct Stack *createStack()
|
||||||
{
|
{
|
||||||
struct Stack* stack=malloc(sizeof(struct Stack));
|
struct Stack *stack = malloc(sizeof(struct Stack));
|
||||||
stack->top=-1;
|
stack->top = -1;
|
||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
//Pushes element into stack
|
// Pushes element into stack
|
||||||
void push(struct Stack* stack,int element)
|
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
|
// Removes element from stack, or returns INT_MIN if stack empty
|
||||||
int pop(struct Stack* stack)
|
int pop(struct Stack *stack)
|
||||||
{
|
{
|
||||||
if(stack->top==-1)
|
if (stack->top == -1)
|
||||||
return INT_MIN;
|
return INT_MIN;
|
||||||
else
|
else
|
||||||
return stack->arr[stack->top--];
|
return stack->arr[stack->top--];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,48 +1,61 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
#define NODES 4
|
#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];
|
int tc[NODES][NODES];
|
||||||
|
|
||||||
void warshall() {
|
void warshall()
|
||||||
int i, s, t;
|
{
|
||||||
for (s = 0; s < NODES; s++)
|
int i, s, t;
|
||||||
for (t = 0; t < NODES; t++)
|
for (s = 0; s < NODES; s++)
|
||||||
tc[s][t] = digraph[s][t];
|
for (t = 0; t < NODES; t++)
|
||||||
|
tc[s][t] = digraph[s][t];
|
||||||
|
|
||||||
for (i = 0; i < NODES; i++)
|
for (i = 0; i < NODES; i++)
|
||||||
for (s = 0; s < NODES; s++)
|
for (s = 0; s < NODES; s++)
|
||||||
for (t = 0; t < NODES; t++)
|
for (t = 0; t < NODES; t++)
|
||||||
if (tc[s][i] && tc[i][t])
|
if (tc[s][i] && tc[i][t])
|
||||||
tc[s][t] = 1;
|
tc[s][t] = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void) {
|
int main(void)
|
||||||
warshall();
|
{
|
||||||
int i, j;
|
warshall();
|
||||||
for (i = 0; i < NODES; i++) {
|
int i, j;
|
||||||
for (j = 0; j < NODES; j++) {
|
for (i = 0; i < NODES; i++)
|
||||||
printf("%d ", tc[i][j]);
|
{
|
||||||
}
|
for (j = 0; j < NODES; j++)
|
||||||
putchar('\n');
|
{
|
||||||
}
|
printf("%d ", tc[i][j]);
|
||||||
return 0;
|
}
|
||||||
|
putchar('\n');
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// By
|
// By
|
||||||
// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------.
|
// .----------------. .----------------. .----------------.
|
||||||
// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |
|
// .-----------------. .----------------. .----------------.
|
||||||
// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | |
|
// | .--------------. || .--------------. || .--------------. ||
|
||||||
// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | |
|
// .--------------. | | .--------------. || .--------------. | | | _________ |
|
||||||
// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | |
|
// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____
|
||||||
// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \
|
||||||
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | |
|
// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | |
|
||||||
// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | |
|
// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | |
|
||||||
// | | | || | | || | | || | | | | | | || | | |
|
// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || |
|
||||||
// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |
|
// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | |
|
||||||
// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
|
// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_
|
||||||
|
// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.'
|
||||||
|
// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.'
|
||||||
|
// | | | | | || | | || | | || | | | | |
|
||||||
|
// | || | | | | '--------------' || '--------------' ||
|
||||||
|
// '--------------' || '--------------' | | '--------------' || '--------------'
|
||||||
|
// |
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
// '----------------' '----------------' '----------------'
|
||||||
|
|
||||||
// Email : z5261243@unsw.edu.au
|
// Email : z5261243@unsw.edu.au
|
||||||
// hhoanhtuann@gmail.com
|
// 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)
|
unsigned put(hash_set_t *set, long long hash, void *value)
|
||||||
{
|
{
|
||||||
if (contains_hash(set, hash)) {
|
if (contains_hash(set, hash))
|
||||||
if (set->keys[retrieve_index_from_hash(hash, set->capacity)] == value) {
|
{
|
||||||
|
if (set->keys[retrieve_index_from_hash(hash, set->capacity)] == value)
|
||||||
|
{
|
||||||
return 0;
|
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)
|
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)
|
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;
|
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;
|
set->keys[retrieve_index_from_hash(hash(value), set->capacity)] = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// adler_32 hash
|
// adler_32 hash
|
||||||
long long hash(void *value)
|
long long hash(void *value)
|
||||||
{
|
{
|
||||||
@ -62,7 +67,8 @@ long long hash(void *value)
|
|||||||
int b = 0;
|
int b = 0;
|
||||||
const int MODADLER = 65521;
|
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;
|
a = (a + str[i]) % MODADLER;
|
||||||
b = (b + a) % MODADLER;
|
b = (b + a) % MODADLER;
|
||||||
}
|
}
|
||||||
@ -79,14 +85,17 @@ void resize(hash_set_t *set)
|
|||||||
{
|
{
|
||||||
void **keys_resized = calloc((set->capacity <<= 1), sizeof(void **));
|
void **keys_resized = calloc((set->capacity <<= 1), sizeof(void **));
|
||||||
|
|
||||||
for (int i = 0; i < set->length; i++) {
|
for (int i = 0; i < set->length; i++)
|
||||||
keys_resized[retrieve_index_from_hash(hash(set->values[i]), set->capacity)] = set->values[i];
|
{
|
||||||
|
keys_resized[retrieve_index_from_hash(hash(set->values[i]),
|
||||||
|
set->capacity)] = set->values[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
free(set->keys);
|
free(set->keys);
|
||||||
|
|
||||||
set->keys = keys_resized;
|
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;
|
set->values = new_values;
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,8 @@
|
|||||||
|
|
||||||
#define DEFAULT_HASH_SET_CAPACITY 1 << 10
|
#define DEFAULT_HASH_SET_CAPACITY 1 << 10
|
||||||
|
|
||||||
typedef struct {
|
typedef struct
|
||||||
|
{
|
||||||
unsigned capacity;
|
unsigned capacity;
|
||||||
unsigned length;
|
unsigned length;
|
||||||
void **values;
|
void **values;
|
||||||
@ -20,11 +21,12 @@ extern int contains(hash_set_t *set, void *value);
|
|||||||
|
|
||||||
int contains_hash(hash_set_t *set, long long hash);
|
int contains_hash(hash_set_t *set, long long hash);
|
||||||
|
|
||||||
extern void delete(hash_set_t *set, void *value);
|
extern void delete (hash_set_t *set, void *value);
|
||||||
|
|
||||||
extern long long hash(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);
|
extern void resize(hash_set_t *set);
|
||||||
|
|
||||||
|
@ -34,7 +34,7 @@ int main()
|
|||||||
|
|
||||||
printf("contains %d ? %d\n", v7, contains(set, &v7));
|
printf("contains %d ? %d\n", v7, contains(set, &v7));
|
||||||
|
|
||||||
delete(set, &v6);
|
delete (set, &v6);
|
||||||
|
|
||||||
printf("contains %d ? %d\n", v6, contains(set, &v6));
|
printf("contains %d ? %d\n", v6, contains(set, &v6));
|
||||||
|
|
||||||
|
@ -1,122 +1,148 @@
|
|||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
#include<stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
typedef struct max_heap{
|
typedef struct max_heap
|
||||||
int *p;
|
{
|
||||||
int size;
|
int *p;
|
||||||
int count;
|
int size;
|
||||||
}Heap;
|
int count;
|
||||||
|
} Heap;
|
||||||
|
|
||||||
Heap* create_heap(Heap* heap); /*Creates a max_heap structure and returns a pointer to the struct*/
|
Heap *create_heap(Heap *heap); /*Creates a max_heap structure and returns a
|
||||||
void down_heapify(Heap* heap, int index);/*Pushes an element downwards in the heap to find its correct position*/
|
pointer to the struct*/
|
||||||
void up_heapify(Heap* heap, int index);/*Pushes an element upwards in the heap to find its correct position*/
|
void down_heapify(Heap *heap, int index); /*Pushes an element downwards in the
|
||||||
void push(Heap* heap, int x);/*Inserts an element in the heap*/
|
heap to find its correct position*/
|
||||||
void pop(Heap* heap);/*Removes the top element from the heap*/
|
void up_heapify(Heap *heap, int index); /*Pushes an element upwards in the heap
|
||||||
int top(Heap* heap);/*Returns the top element of the heap or returns INT_MIN if heap is empty*/
|
to find its correct position*/
|
||||||
int empty(Heap* heap);/*Checks if heap is empty*/
|
void push(Heap *heap, int x); /*Inserts an element in the heap*/
|
||||||
int size(Heap* heap);/*Returns the size of heap*/
|
void pop(Heap *heap); /*Removes the top element from the heap*/
|
||||||
|
int top(Heap *heap); /*Returns the top element of the heap or returns INT_MIN if
|
||||||
|
heap is empty*/
|
||||||
|
int empty(Heap *heap); /*Checks if heap is empty*/
|
||||||
|
int size(Heap *heap); /*Returns the size of heap*/
|
||||||
|
|
||||||
int main(){
|
int main()
|
||||||
Heap* head = create_heap(head);
|
{
|
||||||
push(head, 10);
|
Heap *head = create_heap(head);
|
||||||
printf("Pushing element : 10\n");
|
push(head, 10);
|
||||||
push(head, 3);
|
printf("Pushing element : 10\n");
|
||||||
printf("Pushing element : 3\n");
|
push(head, 3);
|
||||||
push(head, 2);
|
printf("Pushing element : 3\n");
|
||||||
printf("Pushing element : 2\n");
|
push(head, 2);
|
||||||
push(head, 8);
|
printf("Pushing element : 2\n");
|
||||||
printf("Pushing element : 8\n");
|
push(head, 8);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Pushing element : 8\n");
|
||||||
push(head, 1);
|
printf("Top element = %d \n", top(head));
|
||||||
printf("Pushing element : 1\n");
|
push(head, 1);
|
||||||
push(head, 7);
|
printf("Pushing element : 1\n");
|
||||||
printf("Pushing element : 7\n");
|
push(head, 7);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Pushing element : 7\n");
|
||||||
pop(head);
|
printf("Top element = %d \n", top(head));
|
||||||
printf("Popping an element.\n");
|
pop(head);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Popping an element.\n");
|
||||||
pop(head);
|
printf("Top element = %d \n", top(head));
|
||||||
printf("Popping an element.\n");
|
pop(head);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Popping an element.\n");
|
||||||
printf("\n");
|
printf("Top element = %d \n", top(head));
|
||||||
return 0;
|
printf("\n");
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
Heap* create_heap(Heap* heap){
|
Heap *create_heap(Heap *heap)
|
||||||
heap = (Heap *)malloc(sizeof(Heap));
|
{
|
||||||
heap->size = 1;
|
heap = (Heap *)malloc(sizeof(Heap));
|
||||||
heap->p = (int *)malloc(heap->size*sizeof(int));
|
heap->size = 1;
|
||||||
heap->count = 0;
|
heap->p = (int *)malloc(heap->size * sizeof(int));
|
||||||
return heap;
|
heap->count = 0;
|
||||||
|
return heap;
|
||||||
}
|
}
|
||||||
|
|
||||||
void down_heapify(Heap* heap, int index){
|
void down_heapify(Heap *heap, int index)
|
||||||
if(index>=heap->count)return;
|
{
|
||||||
int left = index*2+1;
|
if (index >= heap->count)
|
||||||
int right = index*2+2;
|
return;
|
||||||
int leftflag = 0, rightflag = 0;
|
int left = index * 2 + 1;
|
||||||
|
int right = index * 2 + 2;
|
||||||
int maximum = *((heap->p)+index);
|
int leftflag = 0, rightflag = 0;
|
||||||
if(left<heap->count && maximum<*((heap->p)+left)){
|
|
||||||
maximum = *((heap->p)+left);
|
int maximum = *((heap->p) + index);
|
||||||
leftflag = 1;
|
if (left < heap->count && maximum < *((heap->p) + left))
|
||||||
}
|
{
|
||||||
if(right<heap->count && maximum<*((heap->p)+right)){
|
maximum = *((heap->p) + left);
|
||||||
maximum = *((heap->p)+right);
|
leftflag = 1;
|
||||||
leftflag = 0;
|
}
|
||||||
rightflag = 1;
|
if (right < heap->count && maximum < *((heap->p) + right))
|
||||||
}
|
{
|
||||||
if(leftflag){
|
maximum = *((heap->p) + right);
|
||||||
*((heap->p)+left) = *((heap->p)+index);
|
leftflag = 0;
|
||||||
*((heap->p)+index) = maximum;
|
rightflag = 1;
|
||||||
down_heapify(heap, left);
|
}
|
||||||
}
|
if (leftflag)
|
||||||
if(rightflag){
|
{
|
||||||
*((heap->p)+right) = *((heap->p)+index);
|
*((heap->p) + left) = *((heap->p) + index);
|
||||||
*((heap->p)+index) = maximum;
|
*((heap->p) + index) = maximum;
|
||||||
down_heapify(heap, right);
|
down_heapify(heap, left);
|
||||||
}
|
}
|
||||||
|
if (rightflag)
|
||||||
|
{
|
||||||
|
*((heap->p) + right) = *((heap->p) + index);
|
||||||
|
*((heap->p) + index) = maximum;
|
||||||
|
down_heapify(heap, right);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
void up_heapify(Heap* heap, int index){
|
void up_heapify(Heap *heap, int index)
|
||||||
int parent = (index-1)/2;
|
{
|
||||||
if(parent<0)return;
|
int parent = (index - 1) / 2;
|
||||||
if(*((heap->p)+index)>*((heap->p)+parent)){
|
if (parent < 0)
|
||||||
int temp = *((heap->p)+index);
|
return;
|
||||||
*((heap->p)+index) = *((heap->p)+parent);
|
if (*((heap->p) + index) > *((heap->p) + parent))
|
||||||
*((heap->p)+parent) = temp;
|
{
|
||||||
up_heapify(heap, parent);
|
int temp = *((heap->p) + index);
|
||||||
}
|
*((heap->p) + index) = *((heap->p) + parent);
|
||||||
|
*((heap->p) + parent) = temp;
|
||||||
|
up_heapify(heap, parent);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void push(Heap* heap, int x){
|
void push(Heap *heap, int x)
|
||||||
if(heap->count>=heap->size)return;
|
{
|
||||||
*((heap->p)+heap->count) = x;
|
if (heap->count >= heap->size)
|
||||||
heap->count++;
|
return;
|
||||||
if(4*heap->count >= 3*heap->size){
|
*((heap->p) + heap->count) = x;
|
||||||
heap->size *= 2;
|
heap->count++;
|
||||||
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
|
if (4 * heap->count >= 3 * heap->size)
|
||||||
}
|
{
|
||||||
up_heapify(heap, heap->count - 1);
|
heap->size *= 2;
|
||||||
|
(heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int));
|
||||||
|
}
|
||||||
|
up_heapify(heap, heap->count - 1);
|
||||||
}
|
}
|
||||||
void pop(Heap* heap){
|
void pop(Heap *heap)
|
||||||
if(heap->count==0)return;
|
{
|
||||||
heap->count--;
|
if (heap->count == 0)
|
||||||
int temp = *((heap->p)+heap->count);
|
return;
|
||||||
*((heap->p)+heap->count) = *(heap->p);
|
heap->count--;
|
||||||
*(heap->p) = temp;
|
int temp = *((heap->p) + heap->count);
|
||||||
down_heapify(heap, 0);
|
*((heap->p) + heap->count) = *(heap->p);
|
||||||
if(4*heap->count<=heap->size){
|
*(heap->p) = temp;
|
||||||
heap->size /= 2;
|
down_heapify(heap, 0);
|
||||||
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
|
if (4 * heap->count <= heap->size)
|
||||||
}
|
{
|
||||||
|
heap->size /= 2;
|
||||||
|
(heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
int top(Heap* heap){
|
int top(Heap *heap)
|
||||||
if(heap->count!=0)return *(heap->p);
|
{
|
||||||
else return INT_MIN;
|
if (heap->count != 0)
|
||||||
|
return *(heap->p);
|
||||||
|
else
|
||||||
|
return INT_MIN;
|
||||||
}
|
}
|
||||||
int empty(Heap* heap){
|
int empty(Heap *heap)
|
||||||
if(heap->count!=0)return 0;
|
{
|
||||||
else return 1;
|
if (heap->count != 0)
|
||||||
}
|
return 0;
|
||||||
int size(Heap* heap){
|
else
|
||||||
return heap->count;
|
return 1;
|
||||||
}
|
}
|
||||||
|
int size(Heap *heap) { return heap->count; }
|
||||||
|
@ -1,122 +1,148 @@
|
|||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
#include<stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
typedef struct min_heap{
|
typedef struct min_heap
|
||||||
int *p;
|
{
|
||||||
int size;
|
int *p;
|
||||||
int count;
|
int size;
|
||||||
}Heap;
|
int count;
|
||||||
|
} Heap;
|
||||||
|
|
||||||
Heap* create_heap(Heap* heap); /*Creates a min_heap structure and returns a pointer to the struct*/
|
Heap *create_heap(Heap *heap); /*Creates a min_heap structure and returns a
|
||||||
void down_heapify(Heap* heap, int index);/*Pushes an element downwards in the heap to find its correct position*/
|
pointer to the struct*/
|
||||||
void up_heapify(Heap* heap, int index);/*Pushes an element upwards in the heap to find its correct position*/
|
void down_heapify(Heap *heap, int index); /*Pushes an element downwards in the
|
||||||
void push(Heap* heap, int x);/*Inserts an element in the heap*/
|
heap to find its correct position*/
|
||||||
void pop(Heap* heap);/*Removes the top element from the heap*/
|
void up_heapify(Heap *heap, int index); /*Pushes an element upwards in the heap
|
||||||
int top(Heap* heap);/*Returns the top element of the heap or returns INT_MIN if heap is empty*/
|
to find its correct position*/
|
||||||
int empty(Heap* heap);/*Checks if heap is empty*/
|
void push(Heap *heap, int x); /*Inserts an element in the heap*/
|
||||||
int size(Heap* heap);/*Returns the size of heap*/
|
void pop(Heap *heap); /*Removes the top element from the heap*/
|
||||||
|
int top(Heap *heap); /*Returns the top element of the heap or returns INT_MIN if
|
||||||
|
heap is empty*/
|
||||||
|
int empty(Heap *heap); /*Checks if heap is empty*/
|
||||||
|
int size(Heap *heap); /*Returns the size of heap*/
|
||||||
|
|
||||||
int main(){
|
int main()
|
||||||
Heap* head = create_heap(head);
|
{
|
||||||
push(head, 10);
|
Heap *head = create_heap(head);
|
||||||
printf("Pushing element : 10\n");
|
push(head, 10);
|
||||||
push(head, 3);
|
printf("Pushing element : 10\n");
|
||||||
printf("Pushing element : 3\n");
|
push(head, 3);
|
||||||
push(head, 2);
|
printf("Pushing element : 3\n");
|
||||||
printf("Pushing element : 2\n");
|
push(head, 2);
|
||||||
push(head, 8);
|
printf("Pushing element : 2\n");
|
||||||
printf("Pushing element : 8\n");
|
push(head, 8);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Pushing element : 8\n");
|
||||||
push(head, 1);
|
printf("Top element = %d \n", top(head));
|
||||||
printf("Pushing element : 1\n");
|
push(head, 1);
|
||||||
push(head, 7);
|
printf("Pushing element : 1\n");
|
||||||
printf("Pushing element : 7\n");
|
push(head, 7);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Pushing element : 7\n");
|
||||||
pop(head);
|
printf("Top element = %d \n", top(head));
|
||||||
printf("Popping an element.\n");
|
pop(head);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Popping an element.\n");
|
||||||
pop(head);
|
printf("Top element = %d \n", top(head));
|
||||||
printf("Popping an element.\n");
|
pop(head);
|
||||||
printf("Top element = %d \n", top(head));
|
printf("Popping an element.\n");
|
||||||
printf("\n");
|
printf("Top element = %d \n", top(head));
|
||||||
return 0;
|
printf("\n");
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
Heap* create_heap(Heap* heap){
|
Heap *create_heap(Heap *heap)
|
||||||
heap = (Heap *)malloc(sizeof(Heap));
|
{
|
||||||
heap->size = 1;
|
heap = (Heap *)malloc(sizeof(Heap));
|
||||||
heap->p = (int *)malloc(heap->size*sizeof(int));
|
heap->size = 1;
|
||||||
heap->count = 0;
|
heap->p = (int *)malloc(heap->size * sizeof(int));
|
||||||
return heap;
|
heap->count = 0;
|
||||||
|
return heap;
|
||||||
}
|
}
|
||||||
|
|
||||||
void down_heapify(Heap* heap, int index){
|
void down_heapify(Heap *heap, int index)
|
||||||
if(index>=heap->count)return;
|
{
|
||||||
int left = index*2+1;
|
if (index >= heap->count)
|
||||||
int right = index*2+2;
|
return;
|
||||||
int leftflag = 0, rightflag = 0;
|
int left = index * 2 + 1;
|
||||||
|
int right = index * 2 + 2;
|
||||||
int minimum = *((heap->p)+index);
|
int leftflag = 0, rightflag = 0;
|
||||||
if(left<heap->count && minimum>*((heap->p)+left)){
|
|
||||||
minimum = *((heap->p)+left);
|
int minimum = *((heap->p) + index);
|
||||||
leftflag = 1;
|
if (left < heap->count && minimum > *((heap->p) + left))
|
||||||
}
|
{
|
||||||
if(right<heap->count && minimum>*((heap->p)+right)){
|
minimum = *((heap->p) + left);
|
||||||
minimum = *((heap->p)+right);
|
leftflag = 1;
|
||||||
leftflag = 0;
|
}
|
||||||
rightflag = 1;
|
if (right < heap->count && minimum > *((heap->p) + right))
|
||||||
}
|
{
|
||||||
if(leftflag){
|
minimum = *((heap->p) + right);
|
||||||
*((heap->p)+left) = *((heap->p)+index);
|
leftflag = 0;
|
||||||
*((heap->p)+index) = minimum;
|
rightflag = 1;
|
||||||
down_heapify(heap, left);
|
}
|
||||||
}
|
if (leftflag)
|
||||||
if(rightflag){
|
{
|
||||||
*((heap->p)+right) = *((heap->p)+index);
|
*((heap->p) + left) = *((heap->p) + index);
|
||||||
*((heap->p)+index) = minimum;
|
*((heap->p) + index) = minimum;
|
||||||
down_heapify(heap, right);
|
down_heapify(heap, left);
|
||||||
}
|
}
|
||||||
|
if (rightflag)
|
||||||
|
{
|
||||||
|
*((heap->p) + right) = *((heap->p) + index);
|
||||||
|
*((heap->p) + index) = minimum;
|
||||||
|
down_heapify(heap, right);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
void up_heapify(Heap* heap, int index){
|
void up_heapify(Heap *heap, int index)
|
||||||
int parent = (index-1)/2;
|
{
|
||||||
if(parent<0)return;
|
int parent = (index - 1) / 2;
|
||||||
if(*((heap->p)+index)<*((heap->p)+parent)){
|
if (parent < 0)
|
||||||
int temp = *((heap->p)+index);
|
return;
|
||||||
*((heap->p)+index) = *((heap->p)+parent);
|
if (*((heap->p) + index) < *((heap->p) + parent))
|
||||||
*((heap->p)+parent) = temp;
|
{
|
||||||
up_heapify(heap, parent);
|
int temp = *((heap->p) + index);
|
||||||
}
|
*((heap->p) + index) = *((heap->p) + parent);
|
||||||
|
*((heap->p) + parent) = temp;
|
||||||
|
up_heapify(heap, parent);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void push(Heap* heap, int x){
|
void push(Heap *heap, int x)
|
||||||
if(heap->count>=heap->size)return;
|
{
|
||||||
*((heap->p)+heap->count) = x;
|
if (heap->count >= heap->size)
|
||||||
heap->count++;
|
return;
|
||||||
if(4*heap->count >= 3*heap->size){
|
*((heap->p) + heap->count) = x;
|
||||||
heap->size *= 2;
|
heap->count++;
|
||||||
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
|
if (4 * heap->count >= 3 * heap->size)
|
||||||
}
|
{
|
||||||
up_heapify(heap, heap->count - 1);
|
heap->size *= 2;
|
||||||
|
(heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int));
|
||||||
|
}
|
||||||
|
up_heapify(heap, heap->count - 1);
|
||||||
}
|
}
|
||||||
void pop(Heap* heap){
|
void pop(Heap *heap)
|
||||||
if(heap->count==0)return;
|
{
|
||||||
heap->count--;
|
if (heap->count == 0)
|
||||||
int temp = *((heap->p)+heap->count);
|
return;
|
||||||
*((heap->p)+heap->count) = *(heap->p);
|
heap->count--;
|
||||||
*(heap->p) = temp;
|
int temp = *((heap->p) + heap->count);
|
||||||
down_heapify(heap, 0);
|
*((heap->p) + heap->count) = *(heap->p);
|
||||||
if(4*heap->count<=heap->size){
|
*(heap->p) = temp;
|
||||||
heap->size /= 2;
|
down_heapify(heap, 0);
|
||||||
(heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int));
|
if (4 * heap->count <= heap->size)
|
||||||
}
|
{
|
||||||
|
heap->size /= 2;
|
||||||
|
(heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
int top(Heap* heap){
|
int top(Heap *heap)
|
||||||
if(heap->count!=0)return *(heap->p);
|
{
|
||||||
else return INT_MIN;
|
if (heap->count != 0)
|
||||||
|
return *(heap->p);
|
||||||
|
else
|
||||||
|
return INT_MIN;
|
||||||
}
|
}
|
||||||
int empty(Heap* heap){
|
int empty(Heap *heap)
|
||||||
if(heap->count!=0)return 0;
|
{
|
||||||
else return 1;
|
if (heap->count != 0)
|
||||||
}
|
return 0;
|
||||||
int size(Heap* heap){
|
else
|
||||||
return heap->count;
|
return 1;
|
||||||
}
|
}
|
||||||
|
int size(Heap *heap) { return heap->count; }
|
||||||
|
@ -1,185 +1,182 @@
|
|||||||
/* 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
|
/*A priority queue is a special type of queue in which each element is
|
||||||
to its priority. If elements with the same priority occur, they are served according to their order in the queue.
|
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,
|
For example: The element with the highest value is considered as the highest
|
||||||
we can assume the element with the lowest value as the highest priority element. In other cases,
|
priority element. However, in other cases, we can assume the element with the
|
||||||
we can set priorities according to our needs.
|
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.
|
In a queue, the first-in-first-out rule is implemented whereas, in a priority
|
||||||
The element with the highest priority is removed first.
|
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
|
insert() - Would insert an element in a queue
|
||||||
delete() - Would delete the smallest element in the queue
|
delete() - Would delete the smallest element in the queue
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#define NULL ((void *)0)
|
||||||
|
|
||||||
#include <stdio.h>
|
struct node
|
||||||
#include <stdlib.h>
|
|
||||||
#define NULL ((void*)0)
|
|
||||||
|
|
||||||
struct node
|
|
||||||
{
|
{
|
||||||
int data ;
|
int data;
|
||||||
struct node *next ;
|
struct node *next;
|
||||||
} ;
|
};
|
||||||
|
|
||||||
struct node *front , *rear ;
|
struct node *front, *rear;
|
||||||
|
|
||||||
/* This function initializes the queue to empty by making both front and rear as NULL */
|
/* This function initializes the queue to empty by making both front and rear as
|
||||||
void createqueue()
|
* NULL */
|
||||||
|
void createqueue() { front = rear = NULL; }
|
||||||
|
|
||||||
|
int empty()
|
||||||
{
|
{
|
||||||
front=rear=NULL ;
|
if (front == NULL)
|
||||||
|
return 1;
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int empty()
|
void insert(int x)
|
||||||
{
|
{
|
||||||
if(front==NULL)
|
struct node *pnode;
|
||||||
return 1 ;
|
|
||||||
else
|
|
||||||
return 0 ;
|
|
||||||
}
|
|
||||||
|
|
||||||
void insert(int x)
|
pnode = (struct node *)malloc(sizeof(struct node));
|
||||||
{
|
if (pnode == NULL)
|
||||||
struct node *pnode ;
|
|
||||||
|
|
||||||
pnode=(struct node*)malloc(sizeof(struct node)) ;
|
|
||||||
if(pnode==NULL)
|
|
||||||
{
|
|
||||||
printf("Memory overflow. Unable to insert.\n") ;
|
|
||||||
exit(1) ;
|
|
||||||
}
|
|
||||||
|
|
||||||
pnode->data=x ;
|
|
||||||
pnode->next=NULL; /* New node is always last node */
|
|
||||||
|
|
||||||
if(empty())
|
|
||||||
front=rear=pnode ;
|
|
||||||
else
|
|
||||||
{
|
|
||||||
rear->next=pnode ;
|
|
||||||
rear=pnode ;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int removes()
|
|
||||||
{
|
|
||||||
int min ;
|
|
||||||
struct node *follow , *follow1 , *p , *p1 ;
|
|
||||||
|
|
||||||
if(empty())
|
|
||||||
{
|
|
||||||
printf("\nQueue Underflow. Unable to remove.") ;
|
|
||||||
exit(1) ;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* finding the node with minimum value in the APQ.*/
|
|
||||||
p=p1=front ;
|
|
||||||
follow=follow1=NULL ;
|
|
||||||
min=front->data ;
|
|
||||||
while(p!=NULL)
|
|
||||||
{
|
|
||||||
if(p->data<min)
|
|
||||||
{
|
{
|
||||||
min=p->data ;
|
printf("Memory overflow. Unable to insert.\n");
|
||||||
follow1=follow ;
|
exit(1);
|
||||||
p1=p ;
|
|
||||||
}
|
|
||||||
follow=p ;
|
|
||||||
p=p->next ;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Deleting the node with min value */
|
|
||||||
|
|
||||||
if(p1==front) /* deleting first node.*/
|
|
||||||
{
|
|
||||||
front=front->next ;
|
|
||||||
if(front==NULL) /* Deleting the only one node */
|
|
||||||
rear=NULL ;
|
|
||||||
}
|
|
||||||
else if(p1==rear) /* Deleting last node */
|
|
||||||
{
|
|
||||||
rear=follow1 ;
|
|
||||||
rear->next=NULL ;
|
|
||||||
}
|
|
||||||
else /* deleting any other node.*/
|
|
||||||
follow1->next=p1->next ;
|
|
||||||
|
|
||||||
|
|
||||||
free(p1) ;
|
|
||||||
return min ; /* DONT FORGET LAST 2 STATEMENTS.*/
|
|
||||||
}
|
|
||||||
|
|
||||||
void show()
|
|
||||||
{
|
|
||||||
struct node *p ;
|
|
||||||
|
|
||||||
if(empty())
|
|
||||||
printf("Queue empty. No data to display \n") ;
|
|
||||||
else
|
|
||||||
{
|
|
||||||
printf("Queue from front to rear is as shown: \n") ;
|
|
||||||
|
|
||||||
p=front ;
|
|
||||||
while(p!=NULL)
|
|
||||||
{
|
|
||||||
printf("%d ",p->data) ;
|
|
||||||
p=p->next ;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("\n") ;
|
pnode->data = x;
|
||||||
}
|
pnode->next = NULL; /* New node is always last node */
|
||||||
}
|
|
||||||
|
|
||||||
void destroyqueue()
|
if (empty())
|
||||||
{
|
front = rear = pnode;
|
||||||
front=rear=NULL ;
|
else
|
||||||
}
|
|
||||||
|
|
||||||
int main()
|
|
||||||
{
|
|
||||||
int x , ch ;
|
|
||||||
|
|
||||||
createqueue() ;
|
|
||||||
|
|
||||||
|
|
||||||
do
|
|
||||||
{
|
|
||||||
printf("\n\n Menu: \n") ;
|
|
||||||
printf("1:Insert \n") ;
|
|
||||||
printf("2:Remove \n") ;
|
|
||||||
printf("3:exit \n") ;
|
|
||||||
printf("Enter your choice: ") ;
|
|
||||||
scanf("%d",&ch) ;
|
|
||||||
|
|
||||||
switch(ch)
|
|
||||||
{
|
{
|
||||||
case 1:
|
rear->next = pnode;
|
||||||
printf("Enter element to be inserted: ") ;
|
rear = pnode;
|
||||||
scanf("%d",&x) ;
|
|
||||||
insert(x) ;
|
|
||||||
show() ;
|
|
||||||
break ;
|
|
||||||
|
|
||||||
case 2:
|
|
||||||
x=removes() ;
|
|
||||||
printf("Element removed is: %d\n",x) ;
|
|
||||||
show() ;
|
|
||||||
break ;
|
|
||||||
|
|
||||||
case 3:
|
|
||||||
break ;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
while(ch!=3) ;
|
|
||||||
|
|
||||||
destroyqueue() ;
|
int removes()
|
||||||
|
{
|
||||||
|
int min;
|
||||||
|
struct node *follow, *follow1, *p, *p1;
|
||||||
|
|
||||||
return 0;
|
if (empty())
|
||||||
|
{
|
||||||
|
printf("\nQueue Underflow. Unable to remove.");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* finding the node with minimum value in the APQ.*/
|
||||||
|
p = p1 = front;
|
||||||
|
follow = follow1 = NULL;
|
||||||
|
min = front->data;
|
||||||
|
while (p != NULL)
|
||||||
|
{
|
||||||
|
if (p->data < min)
|
||||||
|
{
|
||||||
|
min = p->data;
|
||||||
|
follow1 = follow;
|
||||||
|
p1 = p;
|
||||||
|
}
|
||||||
|
follow = p;
|
||||||
|
p = p->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Deleting the node with min value */
|
||||||
|
|
||||||
|
if (p1 == front) /* deleting first node.*/
|
||||||
|
{
|
||||||
|
front = front->next;
|
||||||
|
if (front == NULL) /* Deleting the only one node */
|
||||||
|
rear = NULL;
|
||||||
|
}
|
||||||
|
else if (p1 == rear) /* Deleting last node */
|
||||||
|
{
|
||||||
|
rear = follow1;
|
||||||
|
rear->next = NULL;
|
||||||
|
}
|
||||||
|
else /* deleting any other node.*/
|
||||||
|
follow1->next = p1->next;
|
||||||
|
|
||||||
|
free(p1);
|
||||||
|
return min; /* DONT FORGET LAST 2 STATEMENTS.*/
|
||||||
|
}
|
||||||
|
|
||||||
|
void show()
|
||||||
|
{
|
||||||
|
struct node *p;
|
||||||
|
|
||||||
|
if (empty())
|
||||||
|
printf("Queue empty. No data to display \n");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Queue from front to rear is as shown: \n");
|
||||||
|
|
||||||
|
p = front;
|
||||||
|
while (p != NULL)
|
||||||
|
{
|
||||||
|
printf("%d ", p->data);
|
||||||
|
p = p->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void destroyqueue() { front = rear = NULL; }
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
int x, ch;
|
||||||
|
|
||||||
|
createqueue();
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
printf("\n\n Menu: \n");
|
||||||
|
printf("1:Insert \n");
|
||||||
|
printf("2:Remove \n");
|
||||||
|
printf("3:exit \n");
|
||||||
|
printf("Enter your choice: ");
|
||||||
|
scanf("%d", &ch);
|
||||||
|
|
||||||
|
switch (ch)
|
||||||
|
{
|
||||||
|
case 1:
|
||||||
|
printf("Enter element to be inserted: ");
|
||||||
|
scanf("%d", &x);
|
||||||
|
insert(x);
|
||||||
|
show();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
x = removes();
|
||||||
|
printf("Element removed is: %d\n", x);
|
||||||
|
show();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 3:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} while (ch != 3);
|
||||||
|
|
||||||
|
destroyqueue();
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output of the Program*/
|
/* Output of the Program*/
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
#include<stdlib.h>
|
#include <stdlib.h>
|
||||||
struct node{
|
struct node
|
||||||
int data;
|
{
|
||||||
struct node *next;
|
int data;
|
||||||
|
struct node *next;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct node *head1 = NULL;
|
struct node *head1 = NULL;
|
||||||
@ -12,37 +13,44 @@ struct node *head2 = NULL;
|
|||||||
|
|
||||||
void merge()
|
void merge()
|
||||||
{
|
{
|
||||||
struct node *temp1 = head1;
|
struct node *temp1 = head1;
|
||||||
struct node *temp2 = head2;
|
struct node *temp2 = head2;
|
||||||
|
|
||||||
struct node *holder1 = NULL;
|
struct node *holder1 = NULL;
|
||||||
struct node *holder2 = 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)
|
while (temp1 != NULL && temp2 != NULL)
|
||||||
{
|
{
|
||||||
holder1 = temp1 -> next;
|
holder1 = temp1->next;
|
||||||
//Storing the address of next node of first linked list
|
// Storing the address of next node of first linked list
|
||||||
temp1->next=temp2;
|
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) {
|
if (holder1 != NULL)
|
||||||
//Making the first node of second linked list point to second node of first linked list
|
{
|
||||||
holder2 = temp2 -> next;
|
// Making the first node of second linked list point to second node
|
||||||
temp2 -> next = holder1;
|
// of first linked list
|
||||||
}
|
holder2 = temp2->next;
|
||||||
temp1=holder1;
|
temp2->next = holder1;
|
||||||
temp2=holder2;
|
}
|
||||||
//Updating the address location of two pointer variables temp1 and temp2
|
temp1 = holder1;
|
||||||
}
|
temp2 = holder2;
|
||||||
|
// 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;
|
printf("%d", temp->data);
|
||||||
while(temp!=NULL){
|
temp = temp->next;
|
||||||
printf("->%d",temp->data);
|
while (temp != NULL)
|
||||||
temp=temp->next;
|
{
|
||||||
|
printf("->%d", temp->data);
|
||||||
|
temp = temp->next;
|
||||||
}
|
}
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
@ -51,53 +59,53 @@ int main()
|
|||||||
{
|
{
|
||||||
// Linked List 1: 1->3->5->7 : Linked List 2: 2->4->6
|
// Linked List 1: 1->3->5->7 : Linked List 2: 2->4->6
|
||||||
// making lists
|
// making lists
|
||||||
struct node *one = (struct node*)malloc(sizeof(struct node));
|
struct node *one = (struct node *)malloc(sizeof(struct node));
|
||||||
struct node *two = (struct node*)malloc(sizeof(struct node));
|
struct node *two = (struct node *)malloc(sizeof(struct node));
|
||||||
struct node *three = (struct node*)malloc(sizeof(struct node));
|
struct node *three = (struct node *)malloc(sizeof(struct node));
|
||||||
struct node *four = (struct node*)malloc(sizeof(struct node));
|
struct node *four = (struct node *)malloc(sizeof(struct node));
|
||||||
struct node *five = (struct node*)malloc(sizeof(struct node));
|
struct node *five = (struct node *)malloc(sizeof(struct node));
|
||||||
struct node *six = (struct node*)malloc(sizeof(struct node));
|
struct node *six = (struct node *)malloc(sizeof(struct node));
|
||||||
struct node *seven = (struct node*)malloc(sizeof(struct node));
|
struct node *seven = (struct node *)malloc(sizeof(struct node));
|
||||||
//Seven nodes are created
|
// Seven nodes are created
|
||||||
|
|
||||||
head1=one;
|
head1 = one;
|
||||||
head2=two;
|
head2 = two;
|
||||||
//head1 points to first node of first linked list
|
// head1 points to first node of first linked list
|
||||||
//head2 points to first node of second linked list
|
// head2 points to first node of second linked list
|
||||||
|
|
||||||
one->data=1;
|
one->data = 1;
|
||||||
one->next=three;
|
one->next = three;
|
||||||
|
|
||||||
two->data=2;
|
two->data = 2;
|
||||||
two->next=four;
|
two->next = four;
|
||||||
|
|
||||||
three->data=3;
|
three->data = 3;
|
||||||
three->next=five;
|
three->next = five;
|
||||||
|
|
||||||
four->data=4;
|
four->data = 4;
|
||||||
four->next=six;
|
four->next = six;
|
||||||
|
|
||||||
five->data=5;
|
five->data = 5;
|
||||||
five->next=seven;
|
five->next = seven;
|
||||||
|
|
||||||
six->data=6;
|
six->data = 6;
|
||||||
six->next=NULL;
|
six->next = NULL;
|
||||||
//Last node of second input linked list
|
// Last node of second input linked list
|
||||||
|
|
||||||
seven->data=7;
|
seven->data = 7;
|
||||||
seven->next=NULL;
|
seven->next = NULL;
|
||||||
//Last node of first input linked list
|
// Last node of first input linked list
|
||||||
|
|
||||||
printf("Linked List 1: ");
|
printf("Linked List 1: ");
|
||||||
printlist(head1);
|
printlist(head1);
|
||||||
printf("\nLinked List 2: ");
|
printf("\nLinked List 2: ");
|
||||||
printlist(head2);
|
printlist(head2);
|
||||||
|
|
||||||
//Merging the two linked list into single linked list
|
// Merging the two linked list into single linked list
|
||||||
merge();
|
merge();
|
||||||
|
|
||||||
printf("\nMerged Linked List: ");
|
printf("\nMerged Linked List: ");
|
||||||
printlist(head1); //list one has been modified
|
printlist(head1); // list one has been modified
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -1,70 +1,69 @@
|
|||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
#include<stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
/* Link list node */
|
/* Link list node */
|
||||||
struct Node
|
struct Node
|
||||||
{
|
{
|
||||||
int data;
|
int data;
|
||||||
struct Node* next;
|
struct Node *next;
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Function to get the middle of the linked list*/
|
/* Function to get the middle of the linked list*/
|
||||||
void printMiddle(struct Node *head)
|
void printMiddle(struct Node *head)
|
||||||
{
|
{
|
||||||
struct Node *slow_ptr = head;
|
struct Node *slow_ptr = head;
|
||||||
struct Node *fast_ptr = head;
|
struct Node *fast_ptr = head;
|
||||||
|
|
||||||
if (head!=NULL)
|
if (head != NULL)
|
||||||
{
|
{
|
||||||
while (fast_ptr != NULL && fast_ptr->next != NULL)
|
while (fast_ptr != NULL && fast_ptr->next != NULL)
|
||||||
{
|
{
|
||||||
fast_ptr = fast_ptr->next->next;
|
fast_ptr = fast_ptr->next->next;
|
||||||
slow_ptr = slow_ptr->next;
|
slow_ptr = slow_ptr->next;
|
||||||
}
|
}
|
||||||
printf("The middle element is [%d]\n\n", slow_ptr->data);
|
printf("The middle element is [%d]\n\n", slow_ptr->data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void push(struct Node** head_ref, int new_data)
|
void push(struct Node **head_ref, int new_data)
|
||||||
{
|
{
|
||||||
/* allocate node */
|
/* allocate node */
|
||||||
struct Node* new_node =
|
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
|
||||||
(struct Node*) malloc(sizeof(struct Node));
|
|
||||||
|
|
||||||
/* put in the data */
|
/* put in the data */
|
||||||
new_node->data = new_data;
|
new_node->data = new_data;
|
||||||
|
|
||||||
/* link the old list off the new node */
|
/* link the old list off the new node */
|
||||||
new_node->next = (*head_ref);
|
new_node->next = (*head_ref);
|
||||||
|
|
||||||
/* move the head to point to the new node */
|
/* move the head to point to the new node */
|
||||||
(*head_ref) = new_node;
|
(*head_ref) = new_node;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A utility function to print a given linked list
|
// A utility function to print a given linked list
|
||||||
void printList(struct Node *ptr)
|
void printList(struct Node *ptr)
|
||||||
{
|
{
|
||||||
while (ptr != NULL)
|
while (ptr != NULL)
|
||||||
{
|
{
|
||||||
printf("%d->", ptr->data);
|
printf("%d->", ptr->data);
|
||||||
ptr = ptr->next;
|
ptr = ptr->next;
|
||||||
}
|
}
|
||||||
printf("NULL\n");
|
printf("NULL\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Drier program to test above function*/
|
/* Drier program to test above function*/
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
/* Start with the empty list */
|
/* Start with the empty list */
|
||||||
struct Node* head = NULL;
|
struct Node *head = NULL;
|
||||||
int i;
|
int i;
|
||||||
|
|
||||||
for (i=5; i>0; i--)
|
for (i = 5; i > 0; i--)
|
||||||
{
|
{
|
||||||
push(&head, i);
|
push(&head, i);
|
||||||
printList(head);
|
printList(head);
|
||||||
printMiddle(head);
|
printMiddle(head);
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -1,149 +1,141 @@
|
|||||||
/* Queue using Linked List - Program to create a queue ADT using linked list. ADT should support the following operations
|
/* Queue using Linked List - Program to create a queue ADT using linked list.
|
||||||
1) Createqueue
|
ADT should support the following operations 1) Createqueue 2) Insert into the
|
||||||
2) Insert into the queue
|
queue 3) Delete from the queue 4) destroyqueue
|
||||||
3) Delete from the queue
|
|
||||||
4) destroyqueue
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* queue q declared globally */
|
/* queue q declared globally */
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#define NULL 0
|
#define NULL 0
|
||||||
|
|
||||||
struct node
|
struct node
|
||||||
{
|
{
|
||||||
int data ;
|
int data;
|
||||||
struct node *next ;
|
struct node *next;
|
||||||
} ;
|
};
|
||||||
|
|
||||||
struct queue
|
struct queue
|
||||||
{
|
{
|
||||||
struct node *front , *rear ;
|
struct node *front, *rear;
|
||||||
} ;
|
};
|
||||||
|
|
||||||
struct queue q ;
|
struct queue q;
|
||||||
|
|
||||||
/* This function initializes the queue to empty by making both front and rear as NULL */
|
/* This function initializes the queue to empty by making both front and rear as
|
||||||
void createqueue()
|
* NULL */
|
||||||
|
void createqueue() { q.front = q.rear = NULL; }
|
||||||
|
|
||||||
|
int empty()
|
||||||
{
|
{
|
||||||
q.front=q.rear=NULL ;
|
if (q.front == NULL)
|
||||||
|
return 1;
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int empty()
|
void insert(int x)
|
||||||
{
|
{
|
||||||
if(q.front==NULL)
|
struct node *pnode;
|
||||||
return 1 ;
|
|
||||||
else
|
|
||||||
return 0 ;
|
|
||||||
}
|
|
||||||
|
|
||||||
void insert(int x)
|
pnode = (struct node *)malloc(sizeof(struct node));
|
||||||
{
|
if (pnode == NULL)
|
||||||
struct node *pnode ;
|
|
||||||
|
|
||||||
pnode=(struct node*)malloc(sizeof(struct node)) ;
|
|
||||||
if(pnode==NULL)
|
|
||||||
{
|
|
||||||
printf("Memory overflow. Unable to insert.\n") ;
|
|
||||||
exit(1) ;
|
|
||||||
}
|
|
||||||
|
|
||||||
pnode->data=x ;
|
|
||||||
pnode->next=NULL ; /* New node is always last node */
|
|
||||||
|
|
||||||
if(empty())
|
|
||||||
q.front=q.rear=pnode ;
|
|
||||||
else
|
|
||||||
{
|
|
||||||
(q.rear)->next=pnode ;
|
|
||||||
q.rear=pnode ;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int removes()
|
|
||||||
{
|
|
||||||
int x ;
|
|
||||||
struct node *p ;
|
|
||||||
|
|
||||||
if(empty())
|
|
||||||
{
|
|
||||||
printf("Queue Underflow. Unable to remove.\n") ;
|
|
||||||
exit(1) ;
|
|
||||||
}
|
|
||||||
|
|
||||||
p=q.front ;
|
|
||||||
x=(q.front)->data ;
|
|
||||||
q.front=(q.front)->next ;
|
|
||||||
if(q.front==NULL) /* Queue contained only one node */
|
|
||||||
q.rear=NULL ;
|
|
||||||
free(p) ;
|
|
||||||
return x ;
|
|
||||||
}
|
|
||||||
|
|
||||||
void show()
|
|
||||||
{
|
|
||||||
struct node *p ;
|
|
||||||
|
|
||||||
if(empty())
|
|
||||||
printf("Queue empty. No data to display \n") ;
|
|
||||||
else
|
|
||||||
{
|
|
||||||
printf("Queue from front to rear is as shown: \n") ;
|
|
||||||
|
|
||||||
p=q.front ;
|
|
||||||
while(p!=NULL)
|
|
||||||
{
|
{
|
||||||
printf("%d ",p->data) ;
|
printf("Memory overflow. Unable to insert.\n");
|
||||||
p=p->next ;
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("\n") ;
|
pnode->data = x;
|
||||||
}
|
pnode->next = NULL; /* New node is always last node */
|
||||||
|
|
||||||
|
if (empty())
|
||||||
|
q.front = q.rear = pnode;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
(q.rear)->next = pnode;
|
||||||
|
q.rear = pnode;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void destroyqueue()
|
int removes()
|
||||||
{
|
{
|
||||||
q.front=q.rear=NULL ;
|
int x;
|
||||||
|
struct node *p;
|
||||||
|
|
||||||
|
if (empty())
|
||||||
|
{
|
||||||
|
printf("Queue Underflow. Unable to remove.\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
p = q.front;
|
||||||
|
x = (q.front)->data;
|
||||||
|
q.front = (q.front)->next;
|
||||||
|
if (q.front == NULL) /* Queue contained only one node */
|
||||||
|
q.rear = NULL;
|
||||||
|
free(p);
|
||||||
|
return x;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void show()
|
||||||
|
{
|
||||||
|
struct node *p;
|
||||||
|
|
||||||
|
if (empty())
|
||||||
|
printf("Queue empty. No data to display \n");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Queue from front to rear is as shown: \n");
|
||||||
|
|
||||||
|
p = q.front;
|
||||||
|
while (p != NULL)
|
||||||
|
{
|
||||||
|
printf("%d ", p->data);
|
||||||
|
p = p->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void destroyqueue() { q.front = q.rear = NULL; }
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int x , ch ;
|
int x, ch;
|
||||||
|
|
||||||
createqueue() ;
|
createqueue();
|
||||||
|
|
||||||
do
|
do
|
||||||
{
|
|
||||||
printf("\n\n Menu: \n") ;
|
|
||||||
printf("1:Insert \n") ;
|
|
||||||
printf("2:Remove \n") ;
|
|
||||||
printf("3:exit \n") ;
|
|
||||||
printf("Enter your choice: ") ;
|
|
||||||
scanf("%d",&ch) ;
|
|
||||||
|
|
||||||
switch(ch)
|
|
||||||
{
|
{
|
||||||
case 1:
|
printf("\n\n Menu: \n");
|
||||||
printf("Enter element to be inserted: ") ;
|
printf("1:Insert \n");
|
||||||
scanf("%d",&x) ;
|
printf("2:Remove \n");
|
||||||
insert(x) ;
|
printf("3:exit \n");
|
||||||
show() ;
|
printf("Enter your choice: ");
|
||||||
break ;
|
scanf("%d", &ch);
|
||||||
|
|
||||||
case 2:
|
switch (ch)
|
||||||
x=removes() ;
|
{
|
||||||
printf("Element removed is: %d\n",x) ;
|
case 1:
|
||||||
show() ;
|
printf("Enter element to be inserted: ");
|
||||||
break ;
|
scanf("%d", &x);
|
||||||
|
insert(x);
|
||||||
|
show();
|
||||||
|
break;
|
||||||
|
|
||||||
case 3:
|
case 2:
|
||||||
break ;
|
x = removes();
|
||||||
}
|
printf("Element removed is: %d\n", x);
|
||||||
}
|
show();
|
||||||
while(ch!=3) ;
|
break;
|
||||||
|
|
||||||
destroyqueue() ;
|
case 3:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} while (ch != 3);
|
||||||
|
|
||||||
return 0;
|
destroyqueue();
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -1,69 +1,71 @@
|
|||||||
/*Includes structure for a node which can be use to make new nodes of the Linked List.
|
/*Includes structure for a node which can be use to make new nodes of the Linked
|
||||||
It is assumed that the data in nodes will be an integer, though
|
List. It is assumed that the data in nodes will be an integer, though function
|
||||||
function can be modified according to the data type, easily.
|
can be modified according to the data type, easily. deleteNode deletes a node
|
||||||
deleteNode deletes a node when passed with a key of the node.
|
when passed with a key of the node.
|
||||||
*/
|
*/
|
||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
struct node
|
struct node
|
||||||
{int info;
|
{
|
||||||
struct node *link;
|
int info;
|
||||||
|
struct node *link;
|
||||||
};
|
};
|
||||||
struct node *start=NULL;
|
struct node *start = NULL;
|
||||||
///////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////
|
||||||
struct node * createnode()//function to create node
|
struct node *createnode() // function to create node
|
||||||
{
|
|
||||||
struct node *t;
|
|
||||||
t=(struct node*)malloc(sizeof(struct node));
|
|
||||||
return(t);
|
|
||||||
}
|
|
||||||
////////////////////////////////////////////////////////
|
|
||||||
void insert()//function to insert at first location
|
|
||||||
{
|
|
||||||
struct node *p;
|
|
||||||
p=createnode();
|
|
||||||
printf("\nenter the number to insert");
|
|
||||||
scanf("%d",&p->info);
|
|
||||||
p->link=NULL;
|
|
||||||
if(start==NULL)
|
|
||||||
{
|
|
||||||
start=p;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
p->link=start;
|
|
||||||
start=p;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
///////////////////////////////////////////////////////////
|
|
||||||
void deletion()//function to delete from first position
|
|
||||||
{
|
{
|
||||||
struct node *t;
|
struct node *t;
|
||||||
if(start==NULL)
|
t = (struct node *)malloc(sizeof(struct node));
|
||||||
|
return (t);
|
||||||
|
}
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
void insert() // function to insert at first location
|
||||||
|
{
|
||||||
|
struct node *p;
|
||||||
|
p = createnode();
|
||||||
|
printf("\nenter the number to insert");
|
||||||
|
scanf("%d", &p->info);
|
||||||
|
p->link = NULL;
|
||||||
|
if (start == NULL)
|
||||||
|
{
|
||||||
|
start = p;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
p->link = start;
|
||||||
|
start = p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
///////////////////////////////////////////////////////////
|
||||||
|
void deletion() // function to delete from first position
|
||||||
|
{
|
||||||
|
struct node *t;
|
||||||
|
if (start == NULL)
|
||||||
{
|
{
|
||||||
printf("\nlist is empty");
|
printf("\nlist is empty");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
struct node *p;
|
struct node *p;
|
||||||
p=start;
|
p = start;
|
||||||
start=start->link;
|
start = start->link;
|
||||||
free(p);
|
free(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
///////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////
|
||||||
void viewlist()//function to display values
|
void viewlist() // function to display values
|
||||||
{
|
{
|
||||||
struct node *p;
|
struct node *p;
|
||||||
if(start==NULL)
|
if (start == NULL)
|
||||||
{
|
{
|
||||||
printf("\nlist is empty");
|
printf("\nlist is empty");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{ p=start;
|
{
|
||||||
while(p!=NULL)
|
p = start;
|
||||||
|
while (p != NULL)
|
||||||
{
|
{
|
||||||
printf("%d ",p->info);
|
printf("%d ", p->info);
|
||||||
p=p->link;
|
p = p->link;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -72,14 +74,14 @@ void viewlist()//function to display values
|
|||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int n;
|
int n;
|
||||||
while(1)
|
while (1)
|
||||||
{
|
{
|
||||||
printf("\n1.add value at first location");
|
printf("\n1.add value at first location");
|
||||||
printf("\n2.delete value from first location");
|
printf("\n2.delete value from first location");
|
||||||
printf("\n3.view value");
|
printf("\n3.view value");
|
||||||
printf("\nenter your choice");
|
printf("\nenter your choice");
|
||||||
scanf("%d",&n);
|
scanf("%d", &n);
|
||||||
switch(n)
|
switch (n)
|
||||||
{
|
{
|
||||||
case 1:
|
case 1:
|
||||||
insert();
|
insert();
|
||||||
@ -94,5 +96,5 @@ int main()
|
|||||||
printf("\ninvalid choice");
|
printf("\ninvalid choice");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return(0);
|
return (0);
|
||||||
}
|
}
|
||||||
|
@ -1,92 +1,85 @@
|
|||||||
#include<stdio.h>
|
#include <stdio.h>
|
||||||
#include<stdlib.h>
|
#include <stdlib.h>
|
||||||
struct node
|
struct node
|
||||||
{
|
{
|
||||||
int info;
|
int info;
|
||||||
struct node *link;
|
struct node *link;
|
||||||
};
|
};
|
||||||
struct node *top=NULL,*temp;
|
struct node *top = NULL, *temp;
|
||||||
void push(struct node*);
|
void push(struct node *);
|
||||||
void pop(struct node*);
|
void pop(struct node *);
|
||||||
void display(struct node*);
|
void display(struct node *);
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int x=0,item;
|
int x = 0, item;
|
||||||
printf("\t****stack using linked list****\n");
|
printf("\t****stack using linked list****\n");
|
||||||
while(x!=4)
|
while (x != 4)
|
||||||
{
|
{
|
||||||
printf("enter your choice");
|
printf("enter your choice");
|
||||||
printf("\n1.push\n2.pop\n3.display\n4.exit\n");
|
printf("\n1.push\n2.pop\n3.display\n4.exit\n");
|
||||||
scanf("%d",&x);
|
scanf("%d", &x);
|
||||||
switch(x)
|
switch (x)
|
||||||
{
|
{
|
||||||
case 1:
|
case 1:
|
||||||
push(top);
|
push(top);
|
||||||
break;
|
break;
|
||||||
case 2: pop(top);
|
case 2:
|
||||||
break;
|
pop(top);
|
||||||
case 3: display(top);
|
break;
|
||||||
break;
|
case 3:
|
||||||
case 4: return 0;
|
display(top);
|
||||||
|
break;
|
||||||
}
|
case 4:
|
||||||
}
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void push(struct node *p)
|
void push(struct node *p)
|
||||||
{
|
{
|
||||||
int item;
|
int item;
|
||||||
struct node *temp;
|
struct node *temp;
|
||||||
temp=(struct node *)malloc(sizeof(struct node));
|
temp = (struct node *)malloc(sizeof(struct node));
|
||||||
printf("enter element to be inserted\n");
|
printf("enter element to be inserted\n");
|
||||||
scanf("%d",&item);
|
scanf("%d", &item);
|
||||||
temp->info=item;
|
temp->info = item;
|
||||||
|
|
||||||
|
|
||||||
|
temp->link = top;
|
||||||
temp->link=top;
|
top = temp;
|
||||||
top=temp;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
printf("inserted succesfully\n");
|
printf("inserted succesfully\n");
|
||||||
}
|
}
|
||||||
void pop(struct node *p)
|
void pop(struct node *p)
|
||||||
{
|
{
|
||||||
int item;
|
int item;
|
||||||
struct node *temp;
|
struct node *temp;
|
||||||
|
|
||||||
if(top==NULL)
|
|
||||||
printf("stack is empty\n");
|
|
||||||
else{
|
|
||||||
item=top->info;
|
|
||||||
temp=top;
|
|
||||||
top=top->link;
|
|
||||||
free(temp);
|
|
||||||
printf("Element popped is%d\n",item);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (top == NULL)
|
||||||
|
printf("stack is empty\n");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
item = top->info;
|
||||||
|
temp = top;
|
||||||
|
top = top->link;
|
||||||
|
free(temp);
|
||||||
|
printf("Element popped is%d\n", item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void display(struct node *p)
|
void display(struct node *p)
|
||||||
{
|
{
|
||||||
|
|
||||||
if(top==NULL)
|
if (top == NULL)
|
||||||
printf("stack is empty\n");
|
printf("stack is empty\n");
|
||||||
else
|
else
|
||||||
{ printf("Elements in the stack are\n");
|
{
|
||||||
while(p!=NULL)
|
printf("Elements in the stack are\n");
|
||||||
{
|
while (p != NULL)
|
||||||
printf("%d\n",p->info);
|
{
|
||||||
p=p->link;
|
printf("%d\n", p->info);
|
||||||
}
|
p = p->link;
|
||||||
|
}
|
||||||
// printf("%d\n",p->info);
|
// printf("%d\n",p->info);
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,22 +1,24 @@
|
|||||||
|
#include "list.h"
|
||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
|
#include <stdarg.h>
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <stdarg.h>
|
|
||||||
#include "list.h"
|
|
||||||
|
|
||||||
#define L List_T
|
#define L List_T
|
||||||
|
|
||||||
/* Initial list */
|
/* Initial list */
|
||||||
L List_init (void) {
|
L List_init(void)
|
||||||
|
{
|
||||||
L list;
|
L list;
|
||||||
list = (L) malloc(sizeof(L));
|
list = (L)malloc(sizeof(L));
|
||||||
list->next = NULL;
|
list->next = NULL;
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Push an element into top of the list */
|
/* 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));
|
L new_elem = (L)malloc(sizeof(L));
|
||||||
new_elem->val = val;
|
new_elem->val = val;
|
||||||
new_elem->next = list;
|
new_elem->next = list;
|
||||||
@ -24,19 +26,22 @@ L List_push(L list, void *val) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Length of list */
|
/* Length of list */
|
||||||
int List_length(L list) {
|
int List_length(L list)
|
||||||
|
{
|
||||||
int n;
|
int n;
|
||||||
for(n = 0; list; list=list->next)
|
for (n = 0; list; list = list->next)
|
||||||
n++;
|
n++;
|
||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Convert list to array */
|
/* Convert list to array */
|
||||||
void **List_toArray(L list) {
|
void **List_toArray(L list)
|
||||||
|
{
|
||||||
int i, n = List_length(list);
|
int i, n = List_length(list);
|
||||||
void **array = (void **)malloc((n+1) *sizeof(*array));
|
void **array = (void **)malloc((n + 1) * sizeof(*array));
|
||||||
|
|
||||||
for(i = 0; i < n; i++) {
|
for (i = 0; i < n; i++)
|
||||||
|
{
|
||||||
array[i] = list->val;
|
array[i] = list->val;
|
||||||
list = list->next;
|
list = list->next;
|
||||||
}
|
}
|
||||||
@ -45,12 +50,14 @@ void **List_toArray(L list) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Create and return a list */
|
/* Create and return a list */
|
||||||
L List_list(L list, void *val, ...) {
|
L List_list(L list, void *val, ...)
|
||||||
|
{
|
||||||
va_list ap;
|
va_list ap;
|
||||||
L *p = &list;
|
L *p = &list;
|
||||||
|
|
||||||
va_start(ap, val);
|
va_start(ap, val);
|
||||||
for(; val; val = va_arg(ap, void *)) {
|
for (; val; val = va_arg(ap, void *))
|
||||||
|
{
|
||||||
*p = malloc(sizeof(L));
|
*p = malloc(sizeof(L));
|
||||||
(*p)->val = val;
|
(*p)->val = val;
|
||||||
p = &(*p)->next;
|
p = &(*p)->next;
|
||||||
@ -61,13 +68,14 @@ L List_list(L list, void *val, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Append 2 lists together */
|
/* Append 2 lists together */
|
||||||
L List_append(L list, L tail) {
|
L List_append(L list, L tail)
|
||||||
|
{
|
||||||
L *p = &list;
|
L *p = &list;
|
||||||
while((*p)->next) {
|
while ((*p)->next)
|
||||||
|
{
|
||||||
p = &(*p)->next;
|
p = &(*p)->next;
|
||||||
}
|
}
|
||||||
|
|
||||||
*p = tail;
|
*p = tail;
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,20 +4,21 @@
|
|||||||
#define L List_T
|
#define L List_T
|
||||||
typedef struct L *L;
|
typedef struct L *L;
|
||||||
|
|
||||||
struct L {
|
struct L
|
||||||
|
{
|
||||||
void *val;
|
void *val;
|
||||||
L next;
|
L next;
|
||||||
};
|
};
|
||||||
|
|
||||||
extern L List_init(void);
|
extern L List_init(void);
|
||||||
extern L List_push(L list, void *val);
|
extern L List_push(L list, void *val);
|
||||||
extern int List_length(L list);
|
extern int List_length(L list);
|
||||||
extern void **List_toArray(L list);
|
extern void **List_toArray(L list);
|
||||||
extern L List_append(L list, L tail);
|
extern L List_append(L list, L tail);
|
||||||
extern L List_list(L list, void *val, ...);
|
extern L List_list(L list, void *val, ...);
|
||||||
/* TODO */
|
/* TODO */
|
||||||
extern L List_copy(L list);
|
extern L List_copy(L list);
|
||||||
extern int List_pop(L *list);
|
extern int List_pop(L *list);
|
||||||
|
|
||||||
#undef L
|
#undef L
|
||||||
#endif
|
#endif
|
||||||
|
@ -1,19 +1,21 @@
|
|||||||
|
#include "list.h"
|
||||||
|
#include <assert.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <assert.h>
|
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include "list.h"
|
|
||||||
|
|
||||||
void print_list(char **array) {
|
void print_list(char **array)
|
||||||
|
{
|
||||||
int i;
|
int i;
|
||||||
for( i = 0; array[i]; i++)
|
for (i = 0; array[i]; i++)
|
||||||
printf("%s", array[i]);
|
printf("%s", array[i]);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
int main()
|
||||||
|
{
|
||||||
List_T list1, list2, list3;
|
List_T list1, list2, list3;
|
||||||
char **str1 = (char **)malloc(100* sizeof(char *));
|
char **str1 = (char **)malloc(100 * sizeof(char *));
|
||||||
|
|
||||||
list1 = List_init();
|
list1 = List_init();
|
||||||
list1 = List_push(list1, "Dang ");
|
list1 = List_push(list1, "Dang ");
|
||||||
|
@ -1,25 +1,26 @@
|
|||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//INCLUDES
|
// INCLUDES
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//MACROS: CONSTANTS
|
// MACROS: CONSTANTS
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//DATA STRUCTURES
|
// DATA STRUCTURES
|
||||||
struct node {
|
struct node
|
||||||
|
{
|
||||||
int data;
|
int data;
|
||||||
struct node* next;
|
struct node *next;
|
||||||
struct node* pre;
|
struct node *pre;
|
||||||
} *head, *tail, *tmp;
|
} * head, *tail, *tmp;
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//GLOBAL VARIABLES
|
// GLOBAL VARIABLES
|
||||||
int count;
|
int count;
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//FORWARD DECLARATIONS
|
// FORWARD DECLARATIONS
|
||||||
void create();
|
void create();
|
||||||
void enque(int x);
|
void enque(int x);
|
||||||
int deque();
|
int deque();
|
||||||
@ -28,19 +29,19 @@ int size();
|
|||||||
int isEmpty();
|
int isEmpty();
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//MAIN ENTRY POINT
|
// MAIN ENTRY POINT
|
||||||
|
|
||||||
int main(int argc, char const *argv[]) {
|
int main(int argc, char const *argv[])
|
||||||
|
{
|
||||||
|
|
||||||
create();
|
create();
|
||||||
enque(5);
|
enque(5);
|
||||||
|
|
||||||
|
return 0;
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void create()
|
||||||
void create() {
|
{
|
||||||
head = NULL;
|
head = NULL;
|
||||||
tail = NULL;
|
tail = NULL;
|
||||||
}
|
}
|
||||||
@ -48,13 +49,17 @@ void create() {
|
|||||||
/**
|
/**
|
||||||
* Puts an item into the Queue.
|
* Puts an item into the Queue.
|
||||||
*/
|
*/
|
||||||
void enque(int x) {
|
void enque(int x)
|
||||||
if(head == NULL) {
|
{
|
||||||
|
if (head == NULL)
|
||||||
|
{
|
||||||
head = (struct node *)malloc(1 * sizeof(struct node));
|
head = (struct node *)malloc(1 * sizeof(struct node));
|
||||||
head->data = x;
|
head->data = x;
|
||||||
head->pre = NULL;
|
head->pre = NULL;
|
||||||
tail = head;
|
tail = head;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
tmp = (struct node *)malloc(1 * sizeof(struct node));
|
tmp = (struct node *)malloc(1 * sizeof(struct node));
|
||||||
tmp->data = x;
|
tmp->data = x;
|
||||||
tmp->next = tail;
|
tmp->next = tail;
|
||||||
@ -65,25 +70,27 @@ void enque(int x) {
|
|||||||
/**
|
/**
|
||||||
* Takes the next item from the Queue.
|
* Takes the next item from the Queue.
|
||||||
*/
|
*/
|
||||||
int deque() {
|
int deque()
|
||||||
|
{
|
||||||
int returnData = 0;
|
int returnData = 0;
|
||||||
if(head == NULL) {
|
if (head == NULL)
|
||||||
|
{
|
||||||
printf("ERROR: Deque from empty queue.\n");
|
printf("ERROR: Deque from empty queue.\n");
|
||||||
exit(1);
|
exit(1);
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
returnData = head->data;
|
returnData = head->data;
|
||||||
if(head->pre == NULL)
|
if (head->pre == NULL)
|
||||||
head = NULL;
|
head = NULL;
|
||||||
else
|
else
|
||||||
head = head->pre;
|
head = head->pre;
|
||||||
head->next = NULL;
|
head->next = NULL;
|
||||||
}
|
}
|
||||||
return returnData;
|
return returnData;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the size of the Queue.
|
* Returns the size of the Queue.
|
||||||
*/
|
*/
|
||||||
int size() {
|
int size() { return count; }
|
||||||
return count;
|
|
||||||
}
|
|
@ -4,27 +4,28 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//INCLUDES
|
// INCLUDES
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//MACROS: CONSTANTS
|
// MACROS: CONSTANTS
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//DATA STRUCTURES
|
// DATA STRUCTURES
|
||||||
struct node {
|
struct node
|
||||||
|
{
|
||||||
int data;
|
int data;
|
||||||
struct node* next;
|
struct node *next;
|
||||||
struct node* pre;
|
struct node *pre;
|
||||||
} *head, *tmp;
|
} * head, *tmp;
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//GLOBAL VARIABLES
|
// GLOBAL VARIABLES
|
||||||
int count = 0;
|
int count = 0;
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//FUNCTION PROTOTYPES
|
// FUNCTION PROTOTYPES
|
||||||
void create();
|
void create();
|
||||||
void push(int x);
|
void push(int x);
|
||||||
int pop();
|
int pop();
|
||||||
@ -33,9 +34,10 @@ int size();
|
|||||||
int isEmpty();
|
int isEmpty();
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
//MAIN ENTRY POINT
|
// MAIN ENTRY POINT
|
||||||
|
|
||||||
int main(int argc, char const *argv[]) {
|
int main(int argc, char const *argv[])
|
||||||
|
{
|
||||||
|
|
||||||
int x, y, z;
|
int x, y, z;
|
||||||
|
|
||||||
@ -52,7 +54,7 @@ int main(int argc, char const *argv[]) {
|
|||||||
y = pop();
|
y = pop();
|
||||||
// 3, 2. Count: 1. Empty: 0;
|
// 3, 2. Count: 1. Empty: 0;
|
||||||
printf("%d, %d.\t\tCount: %d.\tEmpty: %d.\n", x, y, size(), isEmpty());
|
printf("%d, %d.\t\tCount: %d.\tEmpty: %d.\n", x, y, size(), isEmpty());
|
||||||
pop(); // Empty the stack.
|
pop(); // Empty the stack.
|
||||||
|
|
||||||
push(5);
|
push(5);
|
||||||
push(6);
|
push(6);
|
||||||
@ -64,26 +66,28 @@ int main(int argc, char const *argv[]) {
|
|||||||
// 1, 6, 7, 8. Count: 2. Empty: 0.
|
// 1, 6, 7, 8. Count: 2. Empty: 0.
|
||||||
printf("%d, %d, %d.\tCount: %d.\tEmpty: %d.\n", x, y, z, size(), isEmpty());
|
printf("%d, %d, %d.\tCount: %d.\tEmpty: %d.\n", x, y, z, size(), isEmpty());
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the stack to NULL.
|
* Initialize the stack to NULL.
|
||||||
*/
|
*/
|
||||||
void create() {
|
void create() { head = NULL; }
|
||||||
head = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Push data onto the stack.
|
* Push data onto the stack.
|
||||||
*/
|
*/
|
||||||
void push(int x) {
|
void push(int x)
|
||||||
if(head == NULL) {
|
{
|
||||||
|
if (head == NULL)
|
||||||
|
{
|
||||||
head = (struct node *)malloc(1 * sizeof(struct node));
|
head = (struct node *)malloc(1 * sizeof(struct node));
|
||||||
head->next = NULL;
|
head->next = NULL;
|
||||||
head->pre = NULL;
|
head->pre = NULL;
|
||||||
head->data = x;
|
head->data = x;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
tmp = (struct node *)malloc(1 * sizeof(struct node));
|
tmp = (struct node *)malloc(1 * sizeof(struct node));
|
||||||
tmp->data = x;
|
tmp->data = x;
|
||||||
tmp->next = NULL;
|
tmp->next = NULL;
|
||||||
@ -97,19 +101,25 @@ void push(int x) {
|
|||||||
/**
|
/**
|
||||||
* Pop data from the stack
|
* Pop data from the stack
|
||||||
*/
|
*/
|
||||||
int pop() {
|
int pop()
|
||||||
|
{
|
||||||
int returnData;
|
int returnData;
|
||||||
if(head == NULL) {
|
if (head == NULL)
|
||||||
|
{
|
||||||
printf("ERROR: Pop from empty stack.\n");
|
printf("ERROR: Pop from empty stack.\n");
|
||||||
exit(1);
|
exit(1);
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
returnData = head->data;
|
returnData = head->data;
|
||||||
|
|
||||||
if(head->pre == NULL){
|
if (head->pre == NULL)
|
||||||
|
{
|
||||||
free(head);
|
free(head);
|
||||||
head = NULL;
|
head = NULL;
|
||||||
}
|
}
|
||||||
else {
|
else
|
||||||
|
{
|
||||||
head = head->pre;
|
head = head->pre;
|
||||||
free(head->next);
|
free(head->next);
|
||||||
}
|
}
|
||||||
@ -121,10 +131,12 @@ int pop() {
|
|||||||
/**
|
/**
|
||||||
* Returns the next value to be popped.
|
* Returns the next value to be popped.
|
||||||
*/
|
*/
|
||||||
int peek() {
|
int peek()
|
||||||
if(head != NULL)
|
{
|
||||||
|
if (head != NULL)
|
||||||
return head->data;
|
return head->data;
|
||||||
else {
|
else
|
||||||
|
{
|
||||||
printf("ERROR: Peeking from empty stack.");
|
printf("ERROR: Peeking from empty stack.");
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
@ -133,15 +145,14 @@ int peek() {
|
|||||||
/**
|
/**
|
||||||
* Returns the size of the stack.
|
* Returns the size of the stack.
|
||||||
*/
|
*/
|
||||||
int size() {
|
int size() { return count; }
|
||||||
return count;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns 1 if stack is empty, returns 0 if not empty.
|
* Returns 1 if stack is empty, returns 0 if not empty.
|
||||||
*/
|
*/
|
||||||
int isEmpty() {
|
int isEmpty()
|
||||||
if(count == 0)
|
{
|
||||||
|
if (count == 0)
|
||||||
return 1;
|
return 1;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
//program for stack using array
|
// program for stack using array
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
@ -45,7 +45,7 @@ int main()
|
|||||||
return (0);
|
return (0);
|
||||||
}
|
}
|
||||||
|
|
||||||
//function for pushing the element
|
// function for pushing the element
|
||||||
void push()
|
void push()
|
||||||
{
|
{
|
||||||
int n = 0;
|
int n = 0;
|
||||||
@ -55,7 +55,7 @@ void push()
|
|||||||
a[top] = n;
|
a[top] = n;
|
||||||
}
|
}
|
||||||
|
|
||||||
//function for poping the element out
|
// function for poping the element out
|
||||||
void pop()
|
void pop()
|
||||||
{
|
{
|
||||||
if (top == -1)
|
if (top == -1)
|
||||||
@ -71,7 +71,7 @@ void pop()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//function for peeping the element from top of the stack
|
// function for peeping the element from top of the stack
|
||||||
void peek()
|
void peek()
|
||||||
{
|
{
|
||||||
if (top >= 0)
|
if (top >= 0)
|
||||||
@ -80,7 +80,7 @@ void peek()
|
|||||||
printf("\nstack is empty");
|
printf("\nstack is empty");
|
||||||
}
|
}
|
||||||
|
|
||||||
//function to update the element of stack
|
// function to update the element of stack
|
||||||
void update()
|
void update()
|
||||||
{
|
{
|
||||||
int i, n;
|
int i, n;
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
|
#include <assert.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <assert.h>
|
|
||||||
|
|
||||||
#define SIZE 100
|
#define SIZE 100
|
||||||
|
|
||||||
@ -12,14 +12,15 @@ struct node
|
|||||||
};
|
};
|
||||||
|
|
||||||
int c = 0; // c used as counter to check if stack is empty or not
|
int c = 0; // c used as counter to check if stack is empty or not
|
||||||
struct node *head; //declaring head pointer globally assigned to NULL
|
struct node *head; // declaring head pointer globally assigned to NULL
|
||||||
|
|
||||||
void push(char x) //function for pushing
|
void push(char x) // function for pushing
|
||||||
{
|
{
|
||||||
struct node *p = head, *temp;
|
struct node *p = head, *temp;
|
||||||
temp = (struct node *)malloc(sizeof(struct node));
|
temp = (struct node *)malloc(sizeof(struct node));
|
||||||
temp->data = x;
|
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;
|
head = temp;
|
||||||
p = head;
|
p = head;
|
||||||
@ -35,7 +36,7 @@ void push(char x) //function for pushing
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
char pop(void) //function for pop
|
char pop(void) // function for pop
|
||||||
{
|
{
|
||||||
char x;
|
char x;
|
||||||
struct node *p = head;
|
struct node *p = head;
|
||||||
@ -50,14 +51,16 @@ int isBalanced(char *s)
|
|||||||
{
|
{
|
||||||
int i = 0;
|
int i = 0;
|
||||||
char x;
|
char x;
|
||||||
while (s[i] != '\0') //loop for covering entire string of brackets
|
while (s[i] != '\0') // loop for covering entire string of brackets
|
||||||
{
|
{
|
||||||
// printf("\t s[i]=%c\n", s[i]); //DEBUG
|
// 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]);
|
push(s[i]);
|
||||||
else
|
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;
|
return 0;
|
||||||
|
|
||||||
x = pop();
|
x = pop();
|
||||||
@ -71,7 +74,8 @@ int isBalanced(char *s)
|
|||||||
i++;
|
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;
|
return (c == 0) ? 1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,15 +6,15 @@
|
|||||||
of data hiding.
|
of data hiding.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <assert.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <assert.h>
|
|
||||||
|
|
||||||
#include "stack.h"
|
#include "stack.h"
|
||||||
|
|
||||||
/*
|
/*
|
||||||
actual stack data structure
|
actual stack data structure
|
||||||
This pointer will pointing at the actual field (of void * pointers)
|
This pointer will pointing at the actual field (of void * pointers)
|
||||||
that represents the stack.
|
that represents the stack.
|
||||||
*/
|
*/
|
||||||
void **array;
|
void **array;
|
||||||
@ -25,8 +25,8 @@ int max = 10;
|
|||||||
/* counter variable for counting the elements of the stack. */
|
/* counter variable for counting the elements of the stack. */
|
||||||
int counter = 0;
|
int counter = 0;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
offset address
|
offset address
|
||||||
points at the top element of the stack.
|
points at the top element of the stack.
|
||||||
*/
|
*/
|
||||||
int offset = -1;
|
int offset = -1;
|
||||||
@ -42,7 +42,7 @@ void initStack()
|
|||||||
grow: increases the stack by 10 elements.
|
grow: increases the stack by 10 elements.
|
||||||
This utility function isn't part of the public interface
|
This utility function isn't part of the public interface
|
||||||
*/
|
*/
|
||||||
void grow()
|
void grow()
|
||||||
{
|
{
|
||||||
max += 10; /* increases the capacity */
|
max += 10; /* increases the capacity */
|
||||||
|
|
||||||
@ -56,7 +56,7 @@ void grow()
|
|||||||
}
|
}
|
||||||
/*free the memory */
|
/*free the memory */
|
||||||
free(array);
|
free(array);
|
||||||
array = tmp;
|
array = tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* push: pushs the argument onto the stack */
|
/* push: pushs the argument onto the stack */
|
||||||
@ -70,9 +70,9 @@ void push(void *object)
|
|||||||
|
|
||||||
offset++; /* increases the element-pointer */
|
offset++; /* increases the element-pointer */
|
||||||
|
|
||||||
/*
|
/*
|
||||||
moves pointer by the offset address
|
moves pointer by the offset address
|
||||||
pushs the object onto stack
|
pushs the object onto stack
|
||||||
*/
|
*/
|
||||||
*(array + offset) = object;
|
*(array + offset) = object;
|
||||||
|
|
||||||
@ -82,7 +82,7 @@ void push(void *object)
|
|||||||
else /* stack is full */
|
else /* stack is full */
|
||||||
{
|
{
|
||||||
|
|
||||||
grow(); /* lets grow stack */
|
grow(); /* lets grow stack */
|
||||||
push(object); /* recursive call */
|
push(object); /* recursive call */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -114,18 +114,12 @@ void *pop()
|
|||||||
/*
|
/*
|
||||||
size: gets the number of elements of the stack.
|
size: gets the number of elements of the stack.
|
||||||
*/
|
*/
|
||||||
int size()
|
int size() { return counter; }
|
||||||
{
|
|
||||||
return counter;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
isEmpty(): returns 1 if stack is empty otherwise 0.
|
isEmpty(): returns 1 if stack is empty otherwise 0.
|
||||||
*/
|
*/
|
||||||
int isEmpty()
|
int isEmpty() { return counter == 0; }
|
||||||
{
|
|
||||||
return counter == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
top: returns the top element from the stack without removing it.
|
top: returns the top element from the stack without removing it.
|
||||||
|
@ -2,10 +2,9 @@
|
|||||||
author: Christian Bender
|
author: Christian Bender
|
||||||
|
|
||||||
This header represents the public stack-interface.
|
This header represents the public stack-interface.
|
||||||
The stack is generic and self growing.
|
The stack is generic and self growing.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
#ifndef __STACK__
|
#ifndef __STACK__
|
||||||
#define __STACK__
|
#define __STACK__
|
||||||
|
|
||||||
@ -15,15 +14,15 @@
|
|||||||
void initStack();
|
void initStack();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
push: pushs the argument onto the stack
|
push: pushs the argument onto the stack
|
||||||
*/
|
*/
|
||||||
void push(void * object);
|
void push(void *object);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
pop: pops the top element of the stack from the stack.
|
pop: pops the top element of the stack from the stack.
|
||||||
assumes: stack not empty.
|
assumes: stack not empty.
|
||||||
*/
|
*/
|
||||||
void * pop();
|
void *pop();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
size: gets the number of elements of the stack.
|
size: gets the number of elements of the stack.
|
||||||
@ -38,6 +37,6 @@ int isEmpty();
|
|||||||
/*
|
/*
|
||||||
top: returns the top element from the stack without removing it.
|
top: returns the top element from the stack without removing it.
|
||||||
*/
|
*/
|
||||||
void * top();
|
void *top();
|
||||||
|
|
||||||
#endif
|
#endif
|
@ -1,15 +1,16 @@
|
|||||||
|
#include "stack.h"
|
||||||
|
#include <assert.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <assert.h>
|
|
||||||
#include "stack.h"
|
|
||||||
|
|
||||||
int main() {
|
int main()
|
||||||
|
{
|
||||||
Stack_T stk;
|
Stack_T stk;
|
||||||
stk = Stack_init();
|
stk = Stack_init();
|
||||||
Stack_push(stk, (int *) 1);
|
Stack_push(stk, (int *)1);
|
||||||
Stack_push(stk, (int *) 2);
|
Stack_push(stk, (int *)2);
|
||||||
Stack_push(stk, (int *) 3);
|
Stack_push(stk, (int *)3);
|
||||||
Stack_push(stk, (int *) 4);
|
Stack_push(stk, (int *)4);
|
||||||
printf("Size: %d\n", Stack_size(stk));
|
printf("Size: %d\n", Stack_size(stk));
|
||||||
Stack_print(stk);
|
Stack_print(stk);
|
||||||
Stack_pop(stk);
|
Stack_pop(stk);
|
||||||
|
@ -1,48 +1,54 @@
|
|||||||
|
#include "stack.h"
|
||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
#include <stdlib.h>
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include "stack.h"
|
#include <stdlib.h>
|
||||||
|
|
||||||
#define T Stack_T
|
#define T Stack_T
|
||||||
|
|
||||||
typedef struct elem {
|
typedef struct elem
|
||||||
|
{
|
||||||
void *val;
|
void *val;
|
||||||
struct elem *next;
|
struct elem *next;
|
||||||
} elem_t;
|
} elem_t;
|
||||||
|
|
||||||
struct T {
|
struct T
|
||||||
|
{
|
||||||
int count;
|
int count;
|
||||||
elem_t *head;
|
elem_t *head;
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Initial stack */
|
/* Initial stack */
|
||||||
T Stack_init (void) {
|
T Stack_init(void)
|
||||||
|
{
|
||||||
T stack;
|
T stack;
|
||||||
stack = (T) malloc(sizeof(T));
|
stack = (T)malloc(sizeof(T));
|
||||||
stack->count = 0;
|
stack->count = 0;
|
||||||
stack->head = NULL;
|
stack->head = NULL;
|
||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Check empty stack*/
|
/* Check empty stack*/
|
||||||
int Stack_empty(T stack) {
|
int Stack_empty(T stack)
|
||||||
|
{
|
||||||
assert(stack);
|
assert(stack);
|
||||||
return stack->count == 0;
|
return stack->count == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Return size of the stack */
|
/* Return size of the stack */
|
||||||
int Stack_size(T stack) {
|
int Stack_size(T stack)
|
||||||
|
{
|
||||||
assert(stack);
|
assert(stack);
|
||||||
return stack->count;
|
return stack->count;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Push an element into the stack */
|
/* Push an element into the stack */
|
||||||
void Stack_push(T stack, void *val) {
|
void Stack_push(T stack, void *val)
|
||||||
|
{
|
||||||
elem_t *t;
|
elem_t *t;
|
||||||
|
|
||||||
assert(stack);
|
assert(stack);
|
||||||
t = (elem_t *) malloc(sizeof(elem_t));
|
t = (elem_t *)malloc(sizeof(elem_t));
|
||||||
t->val = val;
|
t->val = val;
|
||||||
t->next = stack->head;
|
t->next = stack->head;
|
||||||
stack->head = t;
|
stack->head = t;
|
||||||
@ -50,7 +56,8 @@ void Stack_push(T stack, void *val) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Pop an element out of the stack */
|
/* Pop an element out of the stack */
|
||||||
void *Stack_pop(T stack) {
|
void *Stack_pop(T stack)
|
||||||
|
{
|
||||||
void *val;
|
void *val;
|
||||||
elem_t *t;
|
elem_t *t;
|
||||||
|
|
||||||
@ -65,13 +72,15 @@ void *Stack_pop(T stack) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Print all elements in the stack */
|
/* Print all elements in the stack */
|
||||||
void Stack_print(Stack_T stack) {
|
void Stack_print(Stack_T stack)
|
||||||
|
{
|
||||||
assert(stack);
|
assert(stack);
|
||||||
|
|
||||||
int i, size = Stack_size(stack);
|
int i, size = Stack_size(stack);
|
||||||
elem_t *current_elem = stack->head;
|
elem_t *current_elem = stack->head;
|
||||||
printf("Stack [Top --- Bottom]: ");
|
printf("Stack [Top --- Bottom]: ");
|
||||||
for(i = 0; i < size; ++i) {
|
for (i = 0; i < size; ++i)
|
||||||
|
{
|
||||||
printf("%p ", (int *)current_elem->val);
|
printf("%p ", (int *)current_elem->val);
|
||||||
current_elem = current_elem->next;
|
current_elem = current_elem->next;
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,12 @@
|
|||||||
#define T Stack_T
|
#define T Stack_T
|
||||||
typedef struct T *T;
|
typedef struct T *T;
|
||||||
|
|
||||||
extern T Stack_init (void);
|
extern T Stack_init(void);
|
||||||
extern int Stack_size (T stack);
|
extern int Stack_size(T stack);
|
||||||
extern int Stack_empty (T stack);
|
extern int Stack_empty(T stack);
|
||||||
extern void Stack_push (T stack, void *val);
|
extern void Stack_push(T stack, void *val);
|
||||||
extern void *Stack_pop (T stack);
|
extern void *Stack_pop(T stack);
|
||||||
extern void Stack_print (T stack);
|
extern void Stack_print(T stack);
|
||||||
|
|
||||||
#undef T
|
#undef T
|
||||||
#endif
|
#endif
|
||||||
|
@ -3,8 +3,8 @@
|
|||||||
|
|
||||||
/*-----character - 97 used for get the character from the ASCII value-----*/
|
/*-----character - 97 used for get the character from the ASCII value-----*/
|
||||||
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
@ -16,113 +16,115 @@ typedef struct TrieNode
|
|||||||
struct TrieNode *children[ALPHABET_SIZE];
|
struct TrieNode *children[ALPHABET_SIZE];
|
||||||
char character;
|
char character;
|
||||||
bool isEndOfWord;
|
bool isEndOfWord;
|
||||||
|
|
||||||
} TrieNode;
|
} TrieNode;
|
||||||
|
|
||||||
/*--Create new node--*/
|
/*--Create new node--*/
|
||||||
TrieNode *createTrieNode()
|
TrieNode *createTrieNode()
|
||||||
{
|
{
|
||||||
TrieNode *node;
|
TrieNode *node;
|
||||||
node = malloc(sizeof(TrieNode));
|
node = malloc(sizeof(TrieNode));
|
||||||
node->isEndOfWord = false;
|
node->isEndOfWord = false;
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while(i<ALPHABET_SIZE){
|
while (i < ALPHABET_SIZE)
|
||||||
|
{
|
||||||
node->children[i] = NULL;
|
node->children[i] = NULL;
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*--Insert new word to Trie--*/
|
/*--Insert new word to Trie--*/
|
||||||
void insert(TrieNode *root,char *word)
|
void insert(TrieNode *root, char *word)
|
||||||
{
|
{
|
||||||
/*----Addition of the word done by recurcively----*/
|
/*----Addition of the word done by recurcively----*/
|
||||||
|
|
||||||
//Check wheather word character pointer is NULL
|
// Check wheather word character pointer is NULL
|
||||||
if((strlen(word)-1) != 0)
|
if ((strlen(word) - 1) != 0)
|
||||||
{
|
{
|
||||||
char character = *word;
|
char character = *word;
|
||||||
if(root->children[character-97] == NULL)
|
if (root->children[character - 97] == NULL)
|
||||||
{
|
{
|
||||||
TrieNode *node = NULL;
|
TrieNode *node = NULL;
|
||||||
node = createTrieNode();
|
node = createTrieNode();
|
||||||
node->character = character;
|
node->character = character;
|
||||||
root->children[character-97] = node;
|
root->children[character - 97] = node;
|
||||||
}
|
}
|
||||||
word++;
|
word++;
|
||||||
insert(root->children[character-97],word);
|
insert(root->children[character - 97], word);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
root->isEndOfWord = true;
|
root->isEndOfWord = true;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*--Search a word in the Trie--*/
|
/*--Search a word in the Trie--*/
|
||||||
TrieNode *search( TrieNode *root, char *word)
|
TrieNode *search(TrieNode *root, char *word)
|
||||||
{
|
{
|
||||||
TrieNode *temp;
|
TrieNode *temp;
|
||||||
while(*word != '\0')
|
while (*word != '\0')
|
||||||
{
|
{
|
||||||
char character = *word;
|
char character = *word;
|
||||||
if(root->children[character - 97] != NULL)
|
if (root->children[character - 97] != NULL)
|
||||||
{
|
{
|
||||||
temp = root->children[character-97];
|
temp = root->children[character - 97];
|
||||||
word++;
|
word++;
|
||||||
root = temp;
|
root = temp;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
printf("No possible words!!\n");
|
printf("No possible words!!\n");
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*---Print a word in the array--*/
|
/*---Print a word in the array--*/
|
||||||
void printArray(char chars[], int len)
|
void printArray(char chars[], int len)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
for (i=0; i<len; i++)
|
for (i = 0; i < len; i++)
|
||||||
{
|
{
|
||||||
printf("%c", chars[i]);
|
printf("%c", chars[i]);
|
||||||
}
|
}
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
/*---Return all the related words------*/
|
/*---Return all the related words------*/
|
||||||
void printPathsRecur(TrieNode* node, char prefix[], int filledLen)
|
void printPathsRecur(TrieNode *node, char prefix[], int filledLen)
|
||||||
{
|
{
|
||||||
if (node==NULL) return;
|
if (node == NULL)
|
||||||
|
return;
|
||||||
|
|
||||||
prefix[filledLen] = node->character;
|
prefix[filledLen] = node->character;
|
||||||
filledLen++;
|
filledLen++;
|
||||||
|
|
||||||
if (node->isEndOfWord)
|
if (node->isEndOfWord)
|
||||||
{
|
{
|
||||||
printArray(prefix, filledLen);
|
printArray(prefix, filledLen);
|
||||||
}
|
}
|
||||||
|
|
||||||
int i ;
|
int i;
|
||||||
for(i=0;i<ALPHABET_SIZE;i++)
|
for (i = 0; i < ALPHABET_SIZE; i++)
|
||||||
{
|
{
|
||||||
printPathsRecur(node->children[i], prefix, filledLen);
|
printPathsRecur(node->children[i], prefix, filledLen);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*--Travel through the Trie and return words from it--*/
|
/*--Travel through the Trie and return words from it--*/
|
||||||
void traverse(char prefix[], TrieNode *root)
|
void traverse(char prefix[], TrieNode *root)
|
||||||
{
|
{
|
||||||
TrieNode *temp = NULL;
|
TrieNode *temp = NULL;
|
||||||
temp = search(root,prefix);
|
temp = search(root, prefix);
|
||||||
int j=0;
|
int j = 0;
|
||||||
while(prefix[j]!='\0')
|
while (prefix[j] != '\0')
|
||||||
{
|
{
|
||||||
j++;
|
j++;
|
||||||
}
|
}
|
||||||
printPathsRecur(temp,prefix,j-1);
|
printPathsRecur(temp, prefix, j - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*------Demonstrate purposes uses text file called dictionary -------*/
|
/*------Demonstrate purposes uses text file called dictionary -------*/
|
||||||
@ -137,48 +139,49 @@ char *receiveInput(char *s)
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
//Read the file dictionary
|
// Read the file dictionary
|
||||||
int word_count = 0;
|
int word_count = 0;
|
||||||
char* words[NUMBER_OF_WORDS];
|
char *words[NUMBER_OF_WORDS];
|
||||||
FILE *fp = fopen("dictionary.txt", "r");
|
FILE *fp = fopen("dictionary.txt", "r");
|
||||||
|
|
||||||
if (fp == 0)
|
if (fp == 0)
|
||||||
{
|
{
|
||||||
fprintf(stderr, "Error while opening dictionary file");
|
fprintf(stderr, "Error while opening dictionary file");
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
words[word_count] = malloc(INPUT_WORD_SIZE);
|
words[word_count] = malloc(INPUT_WORD_SIZE);
|
||||||
|
|
||||||
while (fgets(words[word_count], INPUT_WORD_SIZE, fp))
|
while (fgets(words[word_count], INPUT_WORD_SIZE, fp))
|
||||||
{
|
{
|
||||||
word_count++;
|
word_count++;
|
||||||
words[word_count] = malloc(INPUT_WORD_SIZE);
|
words[word_count] = malloc(INPUT_WORD_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Push the words in to Trie
|
||||||
//Push the words in to Trie
|
|
||||||
TrieNode *root = NULL;
|
TrieNode *root = NULL;
|
||||||
root = createTrieNode();
|
root = createTrieNode();
|
||||||
int i;
|
int i;
|
||||||
for(i=0;i<NUMBER_OF_WORDS;i++)
|
for (i = 0; i < NUMBER_OF_WORDS; i++)
|
||||||
{
|
{
|
||||||
insert(root,words[i]);
|
insert(root, words[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (1)
|
while (1)
|
||||||
{
|
{
|
||||||
printf("Enter keyword: ");
|
printf("Enter keyword: ");
|
||||||
char str[100];
|
char str[100];
|
||||||
receiveInput(str);
|
receiveInput(str);
|
||||||
printf("\n==========================================================\n");
|
printf(
|
||||||
|
"\n==========================================================\n");
|
||||||
printf("\n********************* Possible Words ********************\n");
|
printf("\n********************* Possible Words ********************\n");
|
||||||
|
|
||||||
//Find the word through the Trie
|
|
||||||
traverse(str,root);
|
|
||||||
|
|
||||||
printf("\n==========================================================\n");
|
// Find the word through the Trie
|
||||||
|
traverse(str, root);
|
||||||
|
|
||||||
|
printf(
|
||||||
|
"\n==========================================================\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
#include <string.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <ctype.h>
|
#include <ctype.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
char *abbreviate(const char *phrase)
|
char *abbreviate(const char *phrase)
|
||||||
{
|
{
|
||||||
@ -19,8 +19,8 @@ char *abbreviate(const char *phrase)
|
|||||||
/* for -loop variable */
|
/* for -loop variable */
|
||||||
int i = 0;
|
int i = 0;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
counts the empty-characters.
|
counts the empty-characters.
|
||||||
for determine the number of words
|
for determine the number of words
|
||||||
*/
|
*/
|
||||||
while (p_str && (i < 80))
|
while (p_str && (i < 80))
|
||||||
@ -43,7 +43,7 @@ char *abbreviate(const char *phrase)
|
|||||||
/* initalizes words-array with empty strings */
|
/* initalizes words-array with empty strings */
|
||||||
for (i = 0; i < counter; i++)
|
for (i = 0; i < counter; i++)
|
||||||
{
|
{
|
||||||
strcpy(words[i],"");
|
strcpy(words[i], "");
|
||||||
}
|
}
|
||||||
|
|
||||||
/* rewind string */
|
/* rewind string */
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
const char *hello(void)
|
const char *hello(void)
|
||||||
{
|
{
|
||||||
char * ans = strdup("Hello, World!");
|
char *ans = strdup("Hello, World!");
|
||||||
/* string is pointer of the first character */
|
/* string is pointer of the first character */
|
||||||
return ans;
|
return ans;
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
/*
|
/*
|
||||||
is_isogram: returns true if the given string a isogram, otherwise false.
|
is_isogram: returns true if the given string a isogram, otherwise false.
|
||||||
*/
|
*/
|
||||||
bool is_isogram(const char phrase[])
|
bool is_isogram(const char phrase[])
|
||||||
{
|
{
|
||||||
|
|
||||||
/* use 'unsigned' because of the function strlen(...) */
|
/* use 'unsigned' because of the function strlen(...) */
|
||||||
@ -20,18 +20,18 @@ bool is_isogram(const char phrase[])
|
|||||||
/* contains the length of the given string */
|
/* contains the length of the given string */
|
||||||
unsigned int len_phrase = strlen(phrase);
|
unsigned int len_phrase = strlen(phrase);
|
||||||
|
|
||||||
for (i = 0; i < len_phrase; i++ )
|
for (i = 0; i < len_phrase; i++)
|
||||||
{
|
{
|
||||||
current_char = phrase[i];
|
current_char = phrase[i];
|
||||||
|
|
||||||
/* makes sure the current character has no repetition */
|
/* makes sure the current character has no repetition */
|
||||||
for (j = i+1; j < len_phrase; j++)
|
for (j = i + 1; j < len_phrase; j++)
|
||||||
{
|
{
|
||||||
if (current_char == phrase[j])
|
if (current_char == phrase[j])
|
||||||
{
|
{
|
||||||
status = false;
|
status = false;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
because the given string is none isogram.
|
because the given string is none isogram.
|
||||||
that means we can exit the nested for-loop.
|
that means we can exit the nested for-loop.
|
||||||
*/
|
*/
|
||||||
@ -40,7 +40,7 @@ bool is_isogram(const char phrase[])
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* exit label */
|
/* exit label */
|
||||||
end:
|
end:
|
||||||
return status;
|
return status;
|
||||||
}
|
}
|
@ -2,6 +2,6 @@
|
|||||||
#define __RNA_TRANSCRIPTION__H
|
#define __RNA_TRANSCRIPTION__H
|
||||||
|
|
||||||
/* to_rna: compiles a DNA strand in its RNA complement */
|
/* to_rna: compiles a DNA strand in its RNA complement */
|
||||||
char * to_rna(const char s[]);
|
char *to_rna(const char s[]);
|
||||||
|
|
||||||
#endif
|
#endif
|
@ -2,7 +2,7 @@
|
|||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
/*
|
/*
|
||||||
word_count: returns the full number of words in the input_text,
|
word_count: returns the full number of words in the input_text,
|
||||||
otherwise an error code: (see below)
|
otherwise an error code: (see below)
|
||||||
|
|
||||||
error codes: EXCESSIVE_LENGTH_WORD -1
|
error codes: EXCESSIVE_LENGTH_WORD -1
|
||||||
@ -80,7 +80,7 @@ int word_count(const char *input_text, word_count_word_t *words)
|
|||||||
|
|
||||||
for (i = 0; i <= index_list; i++)
|
for (i = 0; i <= index_list; i++)
|
||||||
{
|
{
|
||||||
if (strcmp(word_list[i],words->text) == 0)
|
if (strcmp(word_list[i], words->text) == 0)
|
||||||
{
|
{
|
||||||
words->count++;
|
words->count++;
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
#ifndef WORD_COUNT_H
|
#ifndef WORD_COUNT_H
|
||||||
#define WORD_COUNT_H
|
#define WORD_COUNT_H
|
||||||
|
|
||||||
#define MAX_WORDS 20 // at most MAX_WORDS can be found in the test input string
|
#define MAX_WORDS 20 // at most MAX_WORDS can be found in the test input string
|
||||||
#define MAX_WORD_LENGTH 50 // no individual word can exceed this length
|
#define MAX_WORD_LENGTH 50 // no individual word can exceed this length
|
||||||
|
|
||||||
// results structure
|
// results structure
|
||||||
typedef struct word_count_word {
|
typedef struct word_count_word
|
||||||
char text[MAX_WORD_LENGTH];
|
{
|
||||||
int count;
|
char text[MAX_WORD_LENGTH];
|
||||||
|
int count;
|
||||||
} word_count_word_t;
|
} word_count_word_t;
|
||||||
|
|
||||||
#define EXCESSIVE_LENGTH_WORD -1
|
#define EXCESSIVE_LENGTH_WORD -1
|
||||||
#define EXCESSIVE_NUMBER_OF_WORDS -2
|
#define EXCESSIVE_NUMBER_OF_WORDS -2
|
||||||
|
|
||||||
// word_count - routine to classify the unique words and their frequency in a test input string
|
// word_count - routine to classify the unique words and their frequency in a
|
||||||
// inputs:
|
// test input string inputs:
|
||||||
// input_text = a null-terminated string containing that is analyzed
|
// input_text = a null-terminated string containing that is analyzed
|
||||||
//
|
//
|
||||||
// outputs:
|
// outputs:
|
||||||
@ -22,6 +23,6 @@ typedef struct word_count_word {
|
|||||||
// uniqueWords - number of words in the words structure
|
// uniqueWords - number of words in the words structure
|
||||||
// returns a negative number if an error.
|
// returns a negative number if an error.
|
||||||
// words will contain the results up to that point.
|
// words will contain the results up to that point.
|
||||||
int word_count(const char *input_text, word_count_word_t * words);
|
int word_count(const char *input_text, word_count_word_t *words);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
@ -12,68 +12,77 @@ int dist[MAX];
|
|||||||
int q[MAX];
|
int q[MAX];
|
||||||
int qp = 0;
|
int qp = 0;
|
||||||
|
|
||||||
void enqueue (int v) {
|
void enqueue(int v) { q[qp++] = v; }
|
||||||
q[qp++] = v;
|
|
||||||
|
int cf(void *a, void *b)
|
||||||
|
{
|
||||||
|
int *x = (int *)a;
|
||||||
|
int *y = (int *)b;
|
||||||
|
return *y - *x;
|
||||||
}
|
}
|
||||||
|
|
||||||
int cf (void *a, void *b) {
|
int dequeue()
|
||||||
int *x = (int *)a;
|
{
|
||||||
int *y = (int *)b;
|
qsort(q, qp, sizeof(int), cf);
|
||||||
return *y - *x;
|
return q[--qp];
|
||||||
}
|
}
|
||||||
|
|
||||||
int dequeue () {
|
int queue_has_something() { return (qp > 0); }
|
||||||
qsort(q, qp, sizeof(int), cf);
|
|
||||||
return q[--qp];
|
|
||||||
}
|
|
||||||
|
|
||||||
int queue_has_something () {
|
|
||||||
return (qp > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
int visited[MAX];
|
int visited[MAX];
|
||||||
int vp = 0;
|
int vp = 0;
|
||||||
|
|
||||||
void dijkstra (int s) {
|
void dijkstra(int s)
|
||||||
dist[s] = 0;
|
{
|
||||||
int i;
|
dist[s] = 0;
|
||||||
for (i = 0; i < V; ++i) {
|
int i;
|
||||||
if (i != s) {
|
for (i = 0; i < V; ++i)
|
||||||
dist[i] = INF;
|
{
|
||||||
}
|
if (i != s)
|
||||||
enqueue(i);
|
{
|
||||||
}
|
dist[i] = INF;
|
||||||
while (queue_has_something()) {
|
}
|
||||||
int u = dequeue();
|
enqueue(i);
|
||||||
visited[vp++] = u;
|
}
|
||||||
for (i = 0; i < V; ++i) {
|
while (queue_has_something())
|
||||||
if (mat[u][i]) {
|
{
|
||||||
if (dist[i] > dist[u] + mat[u][i]) {
|
int u = dequeue();
|
||||||
dist[i] = dist[u] + mat[u][i];
|
visited[vp++] = u;
|
||||||
}
|
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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char const *argv[]) {
|
int main(int argc, char const *argv[])
|
||||||
|
{
|
||||||
|
|
||||||
printf("Enter the number of vertices: ");
|
printf("Enter the number of vertices: ");
|
||||||
scanf(" %d", &V);
|
scanf(" %d", &V);
|
||||||
printf("Enter the adj matrix: ");
|
printf("Enter the adj matrix: ");
|
||||||
int i, j;
|
int i, j;
|
||||||
for (i = 0; i < V; ++i) {
|
for (i = 0; i < V; ++i)
|
||||||
for (j = 0; j < V; ++j) {
|
{
|
||||||
scanf(" %d", &mat[i][j]);
|
for (j = 0; j < V; ++j)
|
||||||
}
|
{
|
||||||
}
|
scanf(" %d", &mat[i][j]);
|
||||||
|
}
|
||||||
dijkstra(0);
|
}
|
||||||
|
|
||||||
printf("\nNode\tDist\n");
|
dijkstra(0);
|
||||||
for (i = 0; i < V; ++i) {
|
|
||||||
printf("%d\t%d\n", i, dist[i]);
|
printf("\nNode\tDist\n");
|
||||||
}
|
for (i = 0; i < V; ++i)
|
||||||
|
{
|
||||||
return 0;
|
printf("%d\t%d\n", i, dist[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
10
hash/hash.c
10
hash/hash.c
@ -65,14 +65,16 @@ int adler_32(char s[])
|
|||||||
/* crc32 Hash-Algorithm*/
|
/* crc32 Hash-Algorithm*/
|
||||||
#include <inttypes.h>
|
#include <inttypes.h>
|
||||||
|
|
||||||
uint32_t crc32(char* data){
|
uint32_t crc32(char *data)
|
||||||
|
{
|
||||||
int i = 0;
|
int i = 0;
|
||||||
uint32_t crc = 0xffffffff;
|
uint32_t crc = 0xffffffff;
|
||||||
while(data[i] != '\0'){
|
while (data[i] != '\0')
|
||||||
|
{
|
||||||
uint8_t byte = data[i];
|
uint8_t byte = data[i];
|
||||||
crc = crc ^ byte;
|
crc = crc ^ byte;
|
||||||
for(int j = 8; j > 0; --j)
|
for (int j = 8; j > 0; --j)
|
||||||
crc = (crc >> 1) ^ (0xEDB88320 & ( -(crc & 1)));
|
crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1)));
|
||||||
|
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
|
@ -46,6 +46,4 @@ int adler_32(char[]);
|
|||||||
*/
|
*/
|
||||||
int crc32(char[]);
|
int crc32(char[]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#endif
|
#endif
|
@ -3,8 +3,8 @@
|
|||||||
This file contains a simple test program for each hash-function.
|
This file contains a simple test program for each hash-function.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <stdio.h>
|
|
||||||
#include "hash.h"
|
#include "hash.h"
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
@ -13,7 +13,7 @@ int main(void)
|
|||||||
/* actual tests */
|
/* actual tests */
|
||||||
printf("sdbm: %s --> %llX\n", s, sdbm(s));
|
printf("sdbm: %s --> %llX\n", s, sdbm(s));
|
||||||
printf("djb2: %s --> %llX\n", s, djb2(s));
|
printf("djb2: %s --> %llX\n", s, djb2(s));
|
||||||
printf("xor8: %s --> %X\n", s, xor8(s)); /* 8 bit */
|
printf("xor8: %s --> %X\n", s, xor8(s)); /* 8 bit */
|
||||||
printf("adler_32: %s --> %X\n", s, adler_32(s)); /* 32 bit */
|
printf("adler_32: %s --> %X\n", s, adler_32(s)); /* 32 bit */
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
|
@ -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 i, j;
|
||||||
int *ret = calloc(2, sizeof(int));
|
int *ret = calloc(2, sizeof(int));
|
||||||
for (i = 0; i < numsSize; i++) {
|
for (i = 0; i < numsSize; i++)
|
||||||
|
{
|
||||||
int key = target - nums[i];
|
int key = target - nums[i];
|
||||||
for (j = i + 1; j < numsSize; j++)
|
for (j = i + 1; j < numsSize; j++)
|
||||||
if (nums[j] == key) {
|
if (nums[j] == key)
|
||||||
|
{
|
||||||
ret[0] = i;
|
ret[0] = i;
|
||||||
ret[1] = j;
|
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)
|
if (!left || !right)
|
||||||
return left == right;
|
return left == right;
|
||||||
if (left->val != right->val)
|
if (left->val != right->val)
|
||||||
return 0;
|
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);
|
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)
|
if (a > b)
|
||||||
return a;
|
return a;
|
||||||
else
|
else
|
||||||
return b;
|
return b;
|
||||||
}
|
}
|
||||||
int maxDepth(struct TreeNode* root){
|
int maxDepth(struct TreeNode *root)
|
||||||
|
{
|
||||||
if (root == NULL)
|
if (root == NULL)
|
||||||
return 0;
|
return 0;
|
||||||
else
|
else
|
||||||
return 1 + maxval(maxDepth(root->left), maxDepth(root->right));
|
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)
|
if (left > right)
|
||||||
return NULL;
|
return NULL;
|
||||||
else {
|
else
|
||||||
|
{
|
||||||
int mid = (right + left) / 2;
|
int mid = (right + left) / 2;
|
||||||
struct TreeNode *new_val = malloc(sizeof(struct TreeNode));
|
struct TreeNode *new_val = malloc(sizeof(struct TreeNode));
|
||||||
new_val->val = nums[mid];
|
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)
|
{
|
||||||
|
if (numsSize == 0)
|
||||||
return NULL;
|
return NULL;
|
||||||
else
|
else
|
||||||
return convertBST(nums, 0, numsSize -1);
|
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 i, start = 0;
|
||||||
int *tmp = malloc(arrSize * sizeof(int));
|
int *tmp = malloc(arrSize * sizeof(int));
|
||||||
/* Copy arr into tmp arr */
|
/* Copy arr into tmp arr */
|
||||||
for(i = 0; i < arrSize; i++) {
|
for (i = 0; i < arrSize; i++)
|
||||||
|
{
|
||||||
tmp[i] = arr[i];
|
tmp[i] = arr[i];
|
||||||
}
|
}
|
||||||
i = 0;
|
i = 0;
|
||||||
for(start = 0; start < arrSize; start++) {
|
for (start = 0; start < arrSize; start++)
|
||||||
|
{
|
||||||
arr[start] = tmp[i];
|
arr[start] = tmp[i];
|
||||||
if(tmp[i] == 0) {
|
if (tmp[i] == 0)
|
||||||
|
{
|
||||||
start++;
|
start++;
|
||||||
if (start < arrSize)
|
if (start < arrSize)
|
||||||
arr[start] = 0;
|
arr[start] = 0;
|
||||||
@ -16,5 +20,3 @@ void duplicateZeros(int* arr, int arrSize){
|
|||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,21 +1,23 @@
|
|||||||
struct TreeNode* buildBST(struct ListNode* head, struct ListNode* tail) {
|
struct TreeNode *buildBST(struct ListNode *head, struct ListNode *tail)
|
||||||
if(head == tail)
|
{
|
||||||
|
if (head == tail)
|
||||||
return NULL;
|
return NULL;
|
||||||
struct ListNode* slow = head, *fast = head;
|
struct ListNode *slow = head, *fast = head;
|
||||||
while(fast != tail && fast->next != tail) {
|
while (fast != tail && fast->next != tail)
|
||||||
|
{
|
||||||
fast = fast->next->next;
|
fast = fast->next->next;
|
||||||
slow = slow->next;
|
slow = slow->next;
|
||||||
}
|
}
|
||||||
struct TreeNode* node = malloc(sizeof(struct TreeNode));
|
struct TreeNode *node = malloc(sizeof(struct TreeNode));
|
||||||
node->val = slow->val;
|
node->val = slow->val;
|
||||||
node->left = buildBST(head, slow);
|
node->left = buildBST(head, slow);
|
||||||
node->right = buildBST(slow->next, tail);
|
node->right = buildBST(slow->next, tail);
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
struct TreeNode* sortedListToBST(struct ListNode* head){
|
struct TreeNode *sortedListToBST(struct ListNode *head)
|
||||||
|
{
|
||||||
if (!head)
|
if (!head)
|
||||||
return NULL;
|
return NULL;
|
||||||
else
|
else
|
||||||
return buildBST(head, NULL);
|
return buildBST(head, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,30 +1,28 @@
|
|||||||
//Fucntion to calculate min of values a and b
|
// Fucntion to calculate min of values a and b
|
||||||
int min(int a, int b){
|
int min(int a, int b) { return ((a < b) ? a : b); }
|
||||||
return ((a<b)?a:b);
|
|
||||||
}
|
|
||||||
|
|
||||||
//Two pointer approach to find maximum container area
|
// 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
|
// Start with maximum container width
|
||||||
int start = 0;
|
int start = 0;
|
||||||
int end = heightSize-1;
|
int end = heightSize - 1;
|
||||||
int res = 0;
|
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]);
|
// Calculate current area by taking minimum of two heights
|
||||||
|
int currArea = (end - start) * min(height[start], height[end]);
|
||||||
if(currArea>res)
|
|
||||||
|
if (currArea > res)
|
||||||
res = currArea;
|
res = currArea;
|
||||||
|
|
||||||
if(height[start]<height[end])
|
if (height[start] < height[end])
|
||||||
start = start + 1;
|
start = start + 1;
|
||||||
else
|
else
|
||||||
end = end - 1;
|
end = end - 1;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
int max(int a, int b) {
|
int max(int a, int b) { return a >= b ? a : b; }
|
||||||
return a >= b ? a : b;
|
|
||||||
}
|
|
||||||
|
|
||||||
int height(struct TreeNode* root) {
|
int height(struct TreeNode *root)
|
||||||
|
{
|
||||||
if (root == NULL)
|
if (root == NULL)
|
||||||
return 0;
|
return 0;
|
||||||
else
|
else
|
||||||
return 1 + max(height(root->left), height(root->right));
|
return 1 + max(height(root->left), height(root->right));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool isBalanced(struct TreeNode* root){
|
bool isBalanced(struct TreeNode *root)
|
||||||
|
{
|
||||||
if (root == NULL)
|
if (root == NULL)
|
||||||
return 1;
|
return 1;
|
||||||
int left = height(root->left);
|
int left = height(root->left);
|
||||||
int right = height(root->right);
|
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)
|
if (root == NULL)
|
||||||
return 0;
|
return 0;
|
||||||
if (!root->left && !root->right && sum - root->val == 0)
|
if (!root->left && !root->right && sum - root->val == 0)
|
||||||
return 1;
|
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,16 +1,20 @@
|
|||||||
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;
|
int sum1 = 0, sum2 = 0;
|
||||||
if (start > destination) {
|
if (start > destination)
|
||||||
int tmp = start;
|
{
|
||||||
start = destination;
|
int tmp = start;
|
||||||
destination = tmp;
|
start = destination;
|
||||||
}
|
destination = tmp;
|
||||||
for (auto i = 0; i < distanceSize; ++i) {
|
}
|
||||||
if (i >= start && i < destination)
|
for (auto i = 0; i < distanceSize; ++i)
|
||||||
sum1 += distance[i];
|
{
|
||||||
else
|
if (i >= start && i < destination)
|
||||||
sum2 += distance[i];
|
sum1 += distance[i];
|
||||||
}
|
else
|
||||||
return sum1 < sum2 ? sum1 : sum2;
|
sum2 += distance[i];
|
||||||
|
}
|
||||||
|
return sum1 < sum2 ? sum1 : sum2;
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
int maxNumberOfBalloons(char * text){
|
int maxNumberOfBalloons(char *text)
|
||||||
/*
|
{
|
||||||
0 -> b,
|
/*
|
||||||
|
0 -> b,
|
||||||
1 -> a,
|
1 -> a,
|
||||||
2 -> l,
|
2 -> l,
|
||||||
3 -> o,
|
3 -> o,
|
||||||
@ -8,31 +9,43 @@ int maxNumberOfBalloons(char * text){
|
|||||||
*/
|
*/
|
||||||
int count_letters[5] = {0};
|
int count_letters[5] = {0};
|
||||||
int i, min_counter_ballons;
|
int i, min_counter_ballons;
|
||||||
|
|
||||||
for (char *ptr = text; *ptr; ptr++) {
|
for (char *ptr = text; *ptr; ptr++)
|
||||||
if (*ptr == 'b') {
|
{
|
||||||
|
if (*ptr == 'b')
|
||||||
|
{
|
||||||
count_letters[0]++;
|
count_letters[0]++;
|
||||||
} else if(*ptr == 'a') {
|
}
|
||||||
|
else if (*ptr == 'a')
|
||||||
|
{
|
||||||
count_letters[1]++;
|
count_letters[1]++;
|
||||||
} else if (*ptr == 'l') {
|
}
|
||||||
|
else if (*ptr == 'l')
|
||||||
|
{
|
||||||
count_letters[2]++;
|
count_letters[2]++;
|
||||||
} else if(*ptr == 'o') {
|
}
|
||||||
|
else if (*ptr == 'o')
|
||||||
|
{
|
||||||
count_letters[3]++;
|
count_letters[3]++;
|
||||||
} else if(*ptr == 'n') {
|
}
|
||||||
|
else if (*ptr == 'n')
|
||||||
|
{
|
||||||
count_letters[4]++;
|
count_letters[4]++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Divide by 2 the repeted letters */
|
/* Divide by 2 the repeted letters */
|
||||||
count_letters[2] /= 2;
|
count_letters[2] /= 2;
|
||||||
count_letters[3] /= 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];
|
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)
|
if (count_letters[i] < min_counter_ballons)
|
||||||
min_counter_ballons = count_letters[i];
|
min_counter_ballons = count_letters[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
return min_counter_ballons;
|
return min_counter_ballons;
|
||||||
}
|
}
|
||||||
|
@ -1,164 +1,172 @@
|
|||||||
char *getOne(char c){
|
char *getOne(char c)
|
||||||
switch (c) {
|
{
|
||||||
case '9':
|
switch (c)
|
||||||
return "IX";
|
{
|
||||||
|
case '9':
|
||||||
|
return "IX";
|
||||||
|
|
||||||
case '8':
|
case '8':
|
||||||
return "VIII";
|
return "VIII";
|
||||||
|
|
||||||
case '7':
|
case '7':
|
||||||
return "VII";
|
return "VII";
|
||||||
|
|
||||||
case '6':
|
case '6':
|
||||||
return "VI";
|
return "VI";
|
||||||
|
|
||||||
case '5':
|
case '5':
|
||||||
return "V";
|
return "V";
|
||||||
|
|
||||||
case '4':
|
case '4':
|
||||||
return "IV";
|
return "IV";
|
||||||
|
|
||||||
case '3':
|
case '3':
|
||||||
return "III";
|
return "III";
|
||||||
|
|
||||||
case '2':
|
case '2':
|
||||||
return "II";
|
return "II";
|
||||||
|
|
||||||
case '1':
|
case '1':
|
||||||
return "I";
|
return "I";
|
||||||
|
|
||||||
case '0':
|
case '0':
|
||||||
return "";
|
return "";
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
char *getTen(char c){
|
char *getTen(char c)
|
||||||
switch (c) {
|
{
|
||||||
case '9':
|
switch (c)
|
||||||
return "XC";
|
{
|
||||||
|
case '9':
|
||||||
|
return "XC";
|
||||||
|
|
||||||
case '8':
|
case '8':
|
||||||
return "LXXX";
|
return "LXXX";
|
||||||
|
|
||||||
case '7':
|
case '7':
|
||||||
return "LXX";
|
return "LXX";
|
||||||
|
|
||||||
case '6':
|
case '6':
|
||||||
return "LX";
|
return "LX";
|
||||||
|
|
||||||
case '5':
|
case '5':
|
||||||
return "L";
|
return "L";
|
||||||
|
|
||||||
case '4':
|
case '4':
|
||||||
return "XL";
|
return "XL";
|
||||||
|
|
||||||
case '3':
|
case '3':
|
||||||
return "XXX";
|
return "XXX";
|
||||||
|
|
||||||
case '2':
|
case '2':
|
||||||
return "XX";
|
return "XX";
|
||||||
|
|
||||||
case '1':
|
case '1':
|
||||||
return "X";
|
return "X";
|
||||||
|
|
||||||
case '0':
|
case '0':
|
||||||
return "";
|
return "";
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
char *getHundred(char c){
|
|
||||||
switch (c) {
|
|
||||||
case '9':
|
|
||||||
return "CM";
|
|
||||||
|
|
||||||
case '8':
|
|
||||||
return "DCCC";
|
|
||||||
|
|
||||||
case '7':
|
|
||||||
return "DCC";
|
|
||||||
|
|
||||||
case '6':
|
|
||||||
return "DC";
|
|
||||||
|
|
||||||
case '5':
|
|
||||||
return "D";
|
|
||||||
|
|
||||||
case '4':
|
|
||||||
return "CD";
|
|
||||||
|
|
||||||
case '3':
|
|
||||||
return "CCC";
|
|
||||||
|
|
||||||
case '2':
|
|
||||||
return "CC";
|
|
||||||
|
|
||||||
case '1':
|
|
||||||
return "C";
|
|
||||||
|
|
||||||
case '0':
|
|
||||||
return "";
|
|
||||||
|
|
||||||
default:
|
|
||||||
return NULL;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
char *getThousand(char c){
|
char *getHundred(char c)
|
||||||
switch (c) {
|
{
|
||||||
case '3':
|
switch (c)
|
||||||
return "MMM";
|
{
|
||||||
|
case '9':
|
||||||
|
return "CM";
|
||||||
|
|
||||||
case '2':
|
case '8':
|
||||||
return "MM";
|
return "DCCC";
|
||||||
|
|
||||||
case '1':
|
case '7':
|
||||||
return "M";
|
return "DCC";
|
||||||
|
|
||||||
default:
|
case '6':
|
||||||
return NULL;
|
return "DC";
|
||||||
|
|
||||||
|
case '5':
|
||||||
|
return "D";
|
||||||
|
|
||||||
|
case '4':
|
||||||
|
return "CD";
|
||||||
|
|
||||||
|
case '3':
|
||||||
|
return "CCC";
|
||||||
|
|
||||||
|
case '2':
|
||||||
|
return "CC";
|
||||||
|
|
||||||
|
case '1':
|
||||||
|
return "C";
|
||||||
|
|
||||||
|
case '0':
|
||||||
|
return "";
|
||||||
|
|
||||||
|
default:
|
||||||
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
char *getThousand(char c)
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '3':
|
||||||
|
return "MMM";
|
||||||
|
|
||||||
|
case '2':
|
||||||
|
return "MM";
|
||||||
|
|
||||||
|
case '1':
|
||||||
|
return "M";
|
||||||
|
|
||||||
char * intToRoman(int num){
|
default:
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
char *intToRoman(int num)
|
||||||
|
{
|
||||||
int length;
|
int length;
|
||||||
char number[5];
|
char number[5];
|
||||||
char *s = malloc(16*sizeof(char));
|
char *s = malloc(16 * sizeof(char));
|
||||||
|
|
||||||
sprintf(number, "%i", num);
|
sprintf(number, "%i", num);
|
||||||
|
|
||||||
length = strlen(number);
|
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]));
|
case 4:
|
||||||
break;
|
sprintf(s, "%s%s%s%s", getThousand(number[0]), getHundred(number[1]),
|
||||||
|
getTen(number[2]), getOne(number[3]));
|
||||||
|
break;
|
||||||
|
|
||||||
case 3:
|
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;
|
|
||||||
|
|
||||||
case 2:
|
break;
|
||||||
sprintf(s,"%s%s", getTen(number[0]), getOne(number[1]));
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 1:
|
case 2:
|
||||||
s = getOne(number[0]);
|
sprintf(s, "%s%s", getTen(number[0]), getOne(number[1]));
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
break;
|
||||||
break;
|
|
||||||
|
case 1:
|
||||||
|
s = getOne(number[0]);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
#define MAP_SIZE 2048
|
#define MAP_SIZE 2048
|
||||||
|
|
||||||
int cmpvalue(const void *a, const void *b) {
|
int cmpvalue(const void *a, const void *b) { return *(int *)b - *(int *)a; }
|
||||||
return *(int *)b - *(int *)a;
|
bool uniqueOccurrences(int *arr, int arrSize)
|
||||||
}
|
{
|
||||||
bool uniqueOccurrences(int* arr, int arrSize){
|
|
||||||
int *map = calloc(MAP_SIZE, sizeof(int));
|
int *map = calloc(MAP_SIZE, sizeof(int));
|
||||||
int i;
|
int i;
|
||||||
for(i = 0; i < arrSize; i++) {
|
for (i = 0; i < arrSize; i++)
|
||||||
|
{
|
||||||
if (arr[i] < 0)
|
if (arr[i] < 0)
|
||||||
map[arr[i] + MAP_SIZE/2] += 1;
|
map[arr[i] + MAP_SIZE / 2] += 1;
|
||||||
else
|
else
|
||||||
map[arr[i]] += 1;
|
map[arr[i]] += 1;
|
||||||
}
|
}
|
||||||
@ -16,8 +16,9 @@ bool uniqueOccurrences(int* arr, int arrSize){
|
|||||||
Ex: 3 2 1 0 0 0 0 */
|
Ex: 3 2 1 0 0 0 0 */
|
||||||
qsort(map, MAP_SIZE, sizeof(int), cmpvalue);
|
qsort(map, MAP_SIZE, sizeof(int), cmpvalue);
|
||||||
i = 0;
|
i = 0;
|
||||||
while(map[i]) {
|
while (map[i])
|
||||||
if(map[i] == map[i+1])
|
{
|
||||||
|
if (map[i] == map[i + 1])
|
||||||
return 0;
|
return 0;
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,17 @@
|
|||||||
int maxcmp(int a, int b) {
|
int maxcmp(int a, int b) { return (a >= b) ? a : b; }
|
||||||
return (a >= b)? a : b;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* max subarray problem by using Kadane's Algorithm
|
/* 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
|
/* maxCur: current maximum
|
||||||
*/
|
* maxSoFar: found maximum for subarray so far
|
||||||
int maxCur = 0, maxSoFar = 0;
|
*/
|
||||||
for(int i = 1; i < pricesSize; i++) {
|
int maxCur = 0, maxSoFar = 0;
|
||||||
maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]);
|
for (int i = 1; i < pricesSize; i++)
|
||||||
maxSoFar = maxcmp(maxSoFar, maxCur);
|
{
|
||||||
}
|
maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]);
|
||||||
return maxSoFar;
|
maxSoFar = maxcmp(maxSoFar, maxCur);
|
||||||
|
}
|
||||||
|
return maxSoFar;
|
||||||
}
|
}
|
||||||
|
@ -1,15 +1,21 @@
|
|||||||
bool isPalindrome(char * s){
|
bool isPalindrome(char *s)
|
||||||
|
{
|
||||||
int start = 0, end = strlen(s) - 1;
|
int start = 0, end = strlen(s) - 1;
|
||||||
while(start < end) {
|
while (start < end)
|
||||||
if (!isalpha(s[start]) && !isalnum(s[start])) {
|
{
|
||||||
|
if (!isalpha(s[start]) && !isalnum(s[start]))
|
||||||
|
{
|
||||||
start++;
|
start++;
|
||||||
}
|
}
|
||||||
else if (!isalpha(s[end]) && !isalnum(s[end])) {
|
else if (!isalpha(s[end]) && !isalnum(s[end]))
|
||||||
|
{
|
||||||
end--;
|
end--;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
char c1 = tolower(s[start]);
|
char c1 = tolower(s[start]);
|
||||||
char c2 = tolower(s[end]);
|
char c2 = tolower(s[end]);
|
||||||
if(c1 != c2)
|
if (c1 != c2)
|
||||||
return 0;
|
return 0;
|
||||||
start++;
|
start++;
|
||||||
end--;
|
end--;
|
||||||
|
@ -1,48 +1,57 @@
|
|||||||
int romanToInt(char * s){
|
int romanToInt(char *s)
|
||||||
|
{
|
||||||
int romanToInt = 0;
|
int romanToInt = 0;
|
||||||
for (int i = 0; i < strlen(s); i++) {
|
for (int i = 0; i < strlen(s); i++)
|
||||||
switch(s[i]) {
|
{
|
||||||
case 'I':
|
switch (s[i])
|
||||||
if (i+1 < strlen(s)) {
|
{
|
||||||
if (s[i + 1] == 'V' || s[i + 1] == 'X') {
|
case 'I':
|
||||||
romanToInt -= 1;
|
if (i + 1 < strlen(s))
|
||||||
break;
|
{
|
||||||
}
|
if (s[i + 1] == 'V' || s[i + 1] == 'X')
|
||||||
|
{
|
||||||
|
romanToInt -= 1;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
romanToInt += 1;
|
}
|
||||||
break;
|
romanToInt += 1;
|
||||||
case 'V':
|
break;
|
||||||
romanToInt += 5;
|
case 'V':
|
||||||
break;
|
romanToInt += 5;
|
||||||
case 'X':
|
break;
|
||||||
if (i+1 < strlen(s)) {
|
case 'X':
|
||||||
if (s[i + 1] == 'L' || s[i + 1] == 'C') {
|
if (i + 1 < strlen(s))
|
||||||
romanToInt -= 10;
|
{
|
||||||
break;
|
if (s[i + 1] == 'L' || s[i + 1] == 'C')
|
||||||
}
|
{
|
||||||
|
romanToInt -= 10;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
romanToInt += 10;
|
}
|
||||||
break;
|
romanToInt += 10;
|
||||||
case 'L':
|
break;
|
||||||
romanToInt += 50;
|
case 'L':
|
||||||
break;
|
romanToInt += 50;
|
||||||
case 'C':
|
break;
|
||||||
if (i+1 < strlen(s)) {
|
case 'C':
|
||||||
if (s[i + 1] == 'D' || s[i + 1] == 'M') {
|
if (i + 1 < strlen(s))
|
||||||
romanToInt -= 100;
|
{
|
||||||
break;
|
if (s[i + 1] == 'D' || s[i + 1] == 'M')
|
||||||
}
|
{
|
||||||
|
romanToInt -= 100;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
romanToInt += 100;
|
}
|
||||||
break;
|
romanToInt += 100;
|
||||||
case 'D':
|
break;
|
||||||
romanToInt += 500;
|
case 'D':
|
||||||
break;
|
romanToInt += 500;
|
||||||
case 'M':
|
break;
|
||||||
romanToInt += 1000;
|
case 'M':
|
||||||
break;
|
romanToInt += 1000;
|
||||||
default:
|
break;
|
||||||
break;
|
default:
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return romanToInt;
|
return romanToInt;
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
int singleNumber(int* nums, int numsSize){
|
int singleNumber(int *nums, int numsSize)
|
||||||
|
{
|
||||||
int i, result = 0;
|
int i, result = 0;
|
||||||
for(i = 0; i < numsSize; i++)
|
for (i = 0; i < numsSize; i++)
|
||||||
result = result ^ nums[i];
|
result = result ^ nums[i];
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@ -5,12 +5,15 @@
|
|||||||
* struct ListNode *next;
|
* struct ListNode *next;
|
||||||
* };
|
* };
|
||||||
*/
|
*/
|
||||||
bool hasCycle(struct ListNode *head) {
|
bool hasCycle(struct ListNode *head)
|
||||||
struct ListNode *fast=head, *slow=head;
|
{
|
||||||
while( slow && fast && fast->next ){
|
struct ListNode *fast = head, *slow = head;
|
||||||
fast=fast->next->next;
|
while (slow && fast && fast->next)
|
||||||
slow=slow->next;
|
{
|
||||||
if(fast==slow) return true;
|
fast = fast->next->next;
|
||||||
|
slow = slow->next;
|
||||||
|
if (fast == slow)
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,20 @@
|
|||||||
struct ListNode *detectCycle(struct ListNode *head) {
|
struct ListNode *detectCycle(struct ListNode *head)
|
||||||
|
{
|
||||||
if (head == NULL || head->next == NULL)
|
if (head == NULL || head->next == NULL)
|
||||||
return NULL;
|
return NULL;
|
||||||
struct ListNode *slow, *fast;
|
struct ListNode *slow, *fast;
|
||||||
slow = fast = head;
|
slow = fast = head;
|
||||||
while(fast && fast->next) {
|
while (fast && fast->next)
|
||||||
|
{
|
||||||
slow = slow->next;
|
slow = slow->next;
|
||||||
fast = fast->next->next;
|
fast = fast->next->next;
|
||||||
if(slow == fast) {
|
if (slow == fast)
|
||||||
|
{
|
||||||
struct ListNode *entry = head;
|
struct ListNode *entry = head;
|
||||||
while(slow != entry) {
|
while (slow != entry)
|
||||||
slow = slow -> next;
|
{
|
||||||
entry = entry -> next;
|
slow = slow->next;
|
||||||
|
entry = entry->next;
|
||||||
}
|
}
|
||||||
return entry;
|
return entry;
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
int findMin(int* nums, int numsSize){
|
int findMin(int *nums, int numsSize)
|
||||||
|
{
|
||||||
int low = 0, high = numsSize - 1;
|
int low = 0, high = numsSize - 1;
|
||||||
while (low < high) {
|
while (low < high)
|
||||||
int mid = low + (high - low) / 2;
|
{
|
||||||
|
int mid = low + (high - low) / 2;
|
||||||
/* minimum is on left side */
|
/* minimum is on left side */
|
||||||
if (nums[mid] < nums[high])
|
if (nums[mid] < nums[high])
|
||||||
high = mid;
|
high = mid;
|
||||||
|
@ -1,17 +1,19 @@
|
|||||||
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
|
struct ListNode *getIntersectionNode(struct ListNode *headA,
|
||||||
|
struct ListNode *headB)
|
||||||
|
{
|
||||||
struct ListNode *cur1 = headA, *cur2 = headB;
|
struct ListNode *cur1 = headA, *cur2 = headB;
|
||||||
if(cur1 == NULL || cur2 == NULL)
|
if (cur1 == NULL || cur2 == NULL)
|
||||||
return NULL;
|
return NULL;
|
||||||
while (cur1 && cur2 && cur1 != cur2) {
|
while (cur1 && cur2 && cur1 != cur2)
|
||||||
cur1 = cur1 -> next;
|
{
|
||||||
cur2 = cur2 -> next;
|
cur1 = cur1->next;
|
||||||
|
cur2 = cur2->next;
|
||||||
if (cur1 == cur2)
|
if (cur1 == cur2)
|
||||||
return cur1;
|
return cur1;
|
||||||
if(!cur1)
|
if (!cur1)
|
||||||
cur1 = headB;
|
cur1 = headB;
|
||||||
if(!cur2)
|
if (!cur2)
|
||||||
cur2 = headA;
|
cur2 = headA;
|
||||||
}
|
}
|
||||||
return cur1;
|
return cur1;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,17 @@
|
|||||||
/* Boyer-Moore Majority Vote Algorithm
|
/* Boyer-Moore Majority Vote Algorithm
|
||||||
* http://www.cs.utexas.edu/~moore/best-ideas/mjrty/ */
|
* 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 count = 1;
|
||||||
int majorNum = nums[0];
|
int majorNum = nums[0];
|
||||||
for (int i = 1; i < numsSize; i++) {
|
for (int i = 1; i < numsSize; i++)
|
||||||
if(count == 0) {
|
{
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
majorNum = nums[i];
|
majorNum = nums[i];
|
||||||
count++;
|
count++;
|
||||||
} else if (majorNum == nums[i])
|
}
|
||||||
|
else if (majorNum == nums[i])
|
||||||
count++;
|
count++;
|
||||||
else
|
else
|
||||||
count--;
|
count--;
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user