I'm trying to implement an AVL tree for the first time, and apparently it worked, but I need to change the way of marking the height of the tree, the root node is getting the highest height, but I want to change the root node to have height 0 and go incrementing for the child nodes.
#include <stdio.h>
#include <stdlib.h>
struct NO{
int info;
int altura;
struct NO *esq;
struct NO *dir;
};
typedef struct NO* ArvAVL;
ArvAVL* cria_ArvAVL(){
ArvAVL* raiz = (ArvAVL*) malloc(sizeof(ArvAVL));
if(raiz != NULL)
*raiz = NULL;
return raiz;
}
void libera_NO(struct NO* no){
if(no == NULL)
return;
libera_NO(no->esq);
libera_NO(no->dir);
free(no);
no = NULL;
}
void libera_ArvAVL(ArvAVL* raiz){
if(raiz == NULL)
return;
libera_NO(*raiz);//libera cada nó
free(raiz);//libera a raiz
}
int altura_NO(struct NO* no){
if(no == NULL)
return -1;
else
return no->altura;
}
int fatorBalanceamento_NO(struct NO* no){
return labs(altura_NO(no->esq) - altura_NO(no->dir));
}
int maior(int x, int y){
if(x > y)
return x;
else
return y;
}
void emOrdem_ArvAVL(ArvAVL *raiz){
if(raiz == NULL)
return;
if(*raiz != NULL){
emOrdem_ArvAVL(&((*raiz)->esq));
//printf("%d\n",(*raiz)->info);
printf("%d,%d\n",(*raiz)->info,altura_NO(*raiz));
emOrdem_ArvAVL(&((*raiz)->dir));
}
}
void RotacaoLL(ArvAVL *A){
printf("RotacaoLL\n");
struct NO *B;
B = (*A)->esq;
(*A)->esq = B->dir;
B->dir = *A;
(*A)->altura = maior(altura_NO((*A)->esq),altura_NO((*A)->dir)) + 1;
B->altura = maior(altura_NO(B->esq),(*A)->altura) + 1;
*A = B;
}
void RotacaoRR(ArvAVL *A){
printf("RotacaoRR\n");
struct NO *B;
B = (*A)->dir;
(*A)->dir = B->esq;
B->esq = (*A);
(*A)->altura = maior(altura_NO((*A)->esq),altura_NO((*A)->dir)) + 1;
B->altura = maior(altura_NO(B->dir),(*A)->altura) + 1;
(*A) = B;
}
void RotacaoLR(ArvAVL *A){
RotacaoRR(&(*A)->esq);
RotacaoLL(A);
}
void RotacaoRL(ArvAVL *A){
RotacaoLL(&(*A)->dir);
RotacaoRR(A);
}
int insere_ArvAVL(ArvAVL *raiz, int valor){
int res;
if(*raiz == NULL){
struct NO *novo;
novo = (struct NO*)malloc(sizeof(struct NO));
if(novo == NULL)
return 0;
novo->info = valor;
novo->altura = 0;
novo->esq = NULL;
novo->dir = NULL;
*raiz = novo;
return 1;
}
struct NO *atual = *raiz;
if(valor < atual->info){
if((res = insere_ArvAVL(&(atual->esq), valor)) == 1){
if(fatorBalanceamento_NO(atual) >= 2){
if(valor < (*raiz)->esq->info ){
RotacaoLL(raiz);
}else{
RotacaoLR(raiz);
}
}
}
}else{
if(valor > atual->info){
if((res = insere_ArvAVL(&(atual->dir), valor)) == 1){
if(fatorBalanceamento_NO(atual) >= 2){
if((*raiz)->dir->info < valor){
RotacaoRR(raiz);
}else{
RotacaoRL(raiz);
}
}
}
}else{
printf("Valor duplicado!!\n");
return 0;
}
}
atual->altura = maior(altura_NO(atual->esq),altura_NO(atual->dir)) + 1;
return res;
}
struct NO* procuraMenor(struct NO* atual){
struct NO *no1 = atual;
struct NO *no2 = atual->esq;
while(no2 != NULL){
no1 = no2;
no2 = no2->esq;
}
return no1;
}
int remove_ArvAVL(ArvAVL *raiz, int valor){
if(*raiz == NULL){
printf("valor não existe!!\n");
return 0;
}
int res;
if(valor < (*raiz)->info){
if((res = remove_ArvAVL(&(*raiz)->esq,valor)) == 1){
if(fatorBalanceamento_NO(*raiz) >= 2){
if(altura_NO((*raiz)->dir->esq) >= altura_NO((*raiz)->dir->dir))
RotacaoRR(raiz);
else
RotacaoRL(raiz);
}
}
}
if((*raiz)->info < valor){
if((res = remove_ArvAVL(&(*raiz)->dir, valor)) == 1){
if(fatorBalanceamento_NO(*raiz) >= 2){
if(altura_NO((*raiz)->esq->dir) >= altura_NO((*raiz)->esq->esq) )
RotacaoLL(raiz);
else
RotacaoLR(raiz);
}
}
}
if((*raiz)->info == valor){
if(((*raiz)->esq == NULL || (*raiz)->dir == NULL)){
struct NO *oldNode = (*raiz);
if((*raiz)->esq != NULL)
*raiz = (*raiz)->esq;
else
*raiz = (*raiz)->dir;
free(oldNode);
}else {
struct NO* temp = procuraMenor((*raiz)->dir);
(*raiz)->info = temp->info;
remove_ArvAVL(&(*raiz)->dir, (*raiz)->info);
if(fatorBalanceamento_NO(*raiz) <= -2){
if(altura_NO((*raiz)->esq->dir) >= altura_NO((*raiz)->esq->esq))
RotacaoLL(raiz);
else
RotacaoLR(raiz);
}
}
if (*raiz != NULL)
(*raiz)->altura = maior(altura_NO((*raiz)->esq),altura_NO((*raiz)->dir)) + 1;
return 1;
}
(*raiz)->altura = maior(altura_NO((*raiz)->esq),altura_NO((*raiz)->dir)) + 1;
return res;
}
int main()
{
ArvAVL* avl;
int res,i;
int N = 7, dados[7] = {4,5,1,2,3,7,6};
avl = cria_ArvAVL();
for(i=0;i<N;i++){
res = insere_ArvAVL(avl,dados[i]);
}
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
remove_ArvAVL(avl,6);
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
remove_ArvAVL(avl,7);
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
remove_ArvAVL(avl,4);
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
libera_ArvAVL(avl);
return 0;
}
Current output
1,0
2,1
3,0
4,2
5,0
6,1
7,0
Expected output
1,2
2,1
3,2
4,0
5,2
6,1
7,2
AVL Tree
4
/ \
2 6
/ \ / \
1 3 5 7
Related
I have this code of a red-black tree in which it has the functions mainly of insertion and deletion.
But when trying to perform the deleteNode function, it does not display anything in the output.
being that if I use only the insertion and printing on the screen, the code runs normally.
I believe that the logic is right but I'm doing some manipulation with the struct that is generating the problem.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BLACK 0
#define RED 1
struct RBNo
{
int data;
int cor;
struct RBNo *esq;
struct RBNo *dir;
struct RBNo *pai;
};
struct RBNo *Novo_no_vermelho(int data, struct RBNo *pai){
struct RBNo *novoNO = (struct RBNo *)malloc(sizeof(struct RBNo));
novoNO->pai = pai;
novoNO->esq = novoNO->dir = NULL;
novoNO->cor = RED;
novoNO->data = data;
return novoNO;
}
struct RBNo *Novo_no_preto(int data){
struct RBNo *RBNo = (struct RBNo *)malloc(sizeof(struct RBNo));
RBNo->pai = RBNo->esq = RBNo->dir = NULL;
RBNo->cor = BLACK;
RBNo->data = data;
return RBNo;
}
int filho_esquerda(struct RBNo *raiz){
struct RBNo *pai = raiz->pai;
return (pai->esq == raiz);
}
struct RBNo *Encontrar_irmao(struct RBNo *raiz){
struct RBNo *pai = raiz->pai;
return (filho_esquerda(raiz) ? pai->dir : pai->esq);
}
void RR(struct RBNo *raiz, int mudar_cor){
struct RBNo *pai = raiz->pai;
raiz->pai = pai->pai;
if (pai->pai != NULL){
if(pai->pai->dir == pai)
pai->pai->dir = raiz;
else
pai->pai->esq = raiz;
}
struct RBNo *dir = raiz->dir;
raiz->dir = pai;
pai->pai = raiz;
pai->esq = dir;
if (dir != NULL)
dir->pai = pai;
if (mudar_cor){
raiz->cor = BLACK;
pai->cor = RED;
}
}
void LL(struct RBNo *raiz, int mudar_cor){
struct RBNo *pai = raiz->pai;
raiz->pai = pai->pai;
if (pai->pai != NULL){
if (pai->pai->dir == pai)
pai->pai->dir = raiz;
else
pai->pai->esq = raiz;
}
struct RBNo *esq = raiz->esq;
raiz->esq = pai;
pai->pai = raiz;
pai->dir = esq;
if (esq != NULL)
esq->pai = pai;
if (mudar_cor){
raiz->cor = BLACK;
pai->cor = RED;
}
}
struct RBNo *Insercao(struct RBNo *pai, struct RBNo *raiz, int data){
if (raiz == NULL){
if (pai != NULL)
return Novo_no_vermelho(data, pai);
return Novo_no_preto(data);
}
int na_esquerda;
if (raiz->data > data){
struct RBNo *esq = Insercao(raiz, raiz->esq, data);
if (esq == raiz->pai)
return esq;
raiz->esq = esq;
na_esquerda = 1;
}
else if (raiz->data < data){
struct RBNo *dir = Insercao(raiz, raiz->dir, data);
if (dir == raiz->pai)
return dir;
raiz->dir = dir;
na_esquerda = 0;
}
else
return raiz;
if (na_esquerda){
if (raiz->cor == RED && raiz->esq->cor == RED){
struct RBNo *sibling = Encontrar_irmao(raiz);
if (!sibling || sibling->cor == BLACK){
if (filho_esquerda(raiz))
RR(raiz, 1);
else{
RR(raiz->esq, 0);
raiz = raiz->pai;
LL(raiz, 1);
}
}
else{
raiz->cor = BLACK;
sibling->cor = BLACK;
if (raiz->pai->pai != NULL)
raiz->pai->cor = RED;
}
}
}
else{
if (raiz->cor == RED && raiz->dir->cor == RED){
struct RBNo *sibling = Encontrar_irmao(raiz);
if (!sibling || sibling->cor == BLACK){
if (!filho_esquerda(raiz))
LL(raiz, 1);
else{
LL(raiz->dir, 0);
raiz = raiz->pai;
RR(raiz, 1);
}
}
else{
raiz->cor = BLACK;
sibling->cor = BLACK;
if (raiz->pai->pai != NULL)
raiz->pai->cor = RED;
}
}
}
return raiz;
}
void deleteFix(struct RBNo* x, struct RBNo* node)
{
struct RBNo* s;
while (x != node && x->cor == 0){
if (x == x->pai->esq){
s = x->pai->dir;
if (s->cor == 1){
s->cor = 0;
x->pai->cor = 1;
LL(x->pai, 1);
s = x->pai->dir;
}
if (s->esq->cor == 0 && s->dir->cor == 0)
{
s->cor = 1;
x = x->pai;
}
else
{
if (s->dir->cor == 0)
{
s->esq->cor = 0;
s->cor = 1;
RR(s, 0);
s = x->pai->dir;
}
s->cor = x->pai->cor;
x->pai->cor = 0;
s->dir->cor = 0;
LL(x->pai, 0);
x = node;
}
}
else
{
s = x->pai->esq;
if (s->cor == 1)
{
s->cor = 0;
x->pai->cor = 1;
RR(x->pai, 0);
s = x->pai->esq;
}
if (s->dir->cor == 0 && s->dir->cor == 0)
{
s->cor = 1;
x = x->pai;
}
else
{
if (s->esq->cor == 0)
{
s->dir->cor = 0;
s->cor = 1;
LL(s, 0);
s = x->pai->esq;
}
s->cor = x->pai->cor;
x->pai->cor = 0;
s->esq->cor = 0;
RR(x->pai, 0);
x = node;
}
}
}
x->cor = 0;
}
struct RBNo* minimum(struct RBNo* node)
{
while (node->esq != NULL)
{
node = node->esq;
}
return node;
}
void rbTransplant(struct RBNo* raiz , struct RBNo* u, struct RBNo* v){
if (u->pai == NULL){
raiz = v;
}
else if (u == u->pai->esq)
{
u->pai->esq = v;
}
else
{
u->pai->dir = v;
}
v->pai = u->pai;
}
void deleteNode(struct RBNo* node){
struct RBNo* z = NULL;
struct RBNo* x;
struct RBNo* y;
while (node != NULL){
z = node;
node = node->esq;
}
y = z;
int y_original_cor = y->cor;
if (z->esq == NULL){
x = z->dir;
rbTransplant(node, z, z->dir);
}
else if (z->dir == NULL){
x = z->esq;
rbTransplant(node, z, z->esq);
}
else{
y = minimum(z->dir);
y_original_cor = y->cor;
x = y->dir;
if (y->pai == z){
x->pai = y;
}
else{
rbTransplant(node, y, y->dir);
y->dir = z->dir;
y->dir->pai = y;
}
rbTransplant(node, z, y);
y->esq = z->esq;
y->esq->pai = y;
y->cor = z->cor;
}
free(z);
if (y_original_cor == 0)
{
deleteFix(x, node);
}
}
void Impressao(struct RBNo *raiz, bool ultimo){
if (raiz != NULL){
printf(" ");
if (raiz->cor == 0)
printf("%d BLACK\n", raiz->data);
else
printf("%d RED\n", raiz->data);
Impressao(raiz->esq, false);
Impressao(raiz->dir, true);
}
}
int main()
{
struct RBNo *raiz = NULL;
raiz = Insercao(NULL, raiz, 41);
raiz = Insercao(NULL, raiz, 17);
raiz = Insercao(NULL, raiz, 34);
raiz = Insercao(NULL, raiz, 43);
deleteNode(raiz);
raiz = Insercao(NULL, raiz, 24);
raiz = Insercao(NULL, raiz, 25);
raiz = Insercao(NULL, raiz, 49);
raiz = Insercao(NULL, raiz, 32);
raiz = Insercao(NULL, raiz, 36);
Impressao(raiz, true);
printf("\n");
return 0;
}
That is, the only thing I need is to find out why the code does not display anything when I use the deleteNode function and what is wrong with it, because I'm almost sure that the logic is right.
Good evening forum members.
The following is on the agenda:
Read a sequence of coordinates (x, y, z) of spatial points from the file, ordered by distance from the point of origin (develop a separate function for calculating the distance and store this value in the data structure);
To bypass use the bottom option from right to left;
Extract from the tree all nodes whose z coordinate falls within the specified range zmin ..zmax (I decided to take from 7 to 14) and indicate their number;
To completely erase the tree, use the direct (from the root) version of the bypass from left to right;
Print the entire tree using a non-recursive function.
Please help with number 3. It is not possible to implement the deletion algorithm according to a given condition. It either does not work at all, or errors arrive (
Thanks in advance to everyone who responds
CODE:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_LEN 8
#define STACK_INIT_SIZE 20
typedef struct Tree {
int z;
int viddal;
struct Tree* left, * right;
} TREE;
typedef struct Stack {
size_t size, limit;
TREE** data;
} STACK;
int Distance(FILE* ftxt, int* vid, int* z_cord);
int CreateTreeFromFile(void);
TREE* NewNode(FILE* f, int viddal, int z);
void AddNewNode(TREE* pnew);
void PrintTreeNIZ(TREE* proot);
void iterPostorder(TREE* root);
void OutputTreeStructure(const char* title);
void ShowTree(TREE* proot, int level);
void ShowLevels(void);
int TreeHeight(TREE* proot);
void EraseTree(TREE* proot);
void DeleteSomeNodes(void);
int DeleteNode(TREE* pnew_adr);
TREE* root;
int main(){
system("chcp 1251");
if (CreateTreeFromFile() == 0)
return 0;
puts("\n Created tree: ");
PrintTreeNIZ(root);
OutputTreeStructure("of created tree");
DeleteSomeNodes();
OutputTreeStructure("of the new tree");
EraseTree(root);
root = NULL;
puts("\n Tree was deleted from DM\n\n");
return 0;
}
int Distance(FILE* ftxt, int *vid, int* z_cord) {
TREE* pel = (TREE*)malloc(sizeof(TREE));
if (feof(ftxt)) {;
return NULL;
}
else {
int x, y, z;
fscanf(ftxt, "%d%d%d", &x, &y, &z);
*z_cord = z;
*vid = sqrt(x * x + y * y + z * z);
}
}
int CreateTreeFromFile()
{
const char* fname = "Cords_1.txt";
FILE* fvoc = fopen(fname, "r");
if (fvoc == NULL) {
printf("\n\t\tCan`t open file %s...\n", fname);
return 0;
}
TREE* node;
int viddal, z;
Distance(fvoc, &viddal, &z);
while ((node = NewNode(fvoc, viddal, z)) != NULL) {
AddNewNode(node);
Distance(fvoc, &viddal, &z);
}
fclose(fvoc);
return 1;
}
TREE* NewNode(FILE* f, int viddal, int z)
{
TREE* pel;
pel = (TREE*)malloc(sizeof(TREE));
if (feof(f)) {
return NULL;
}
pel->viddal = viddal;
pel->z = z;
pel->left = pel->right = NULL;
return pel;
}
void AddNewNode(TREE* pnew) {
if (root == NULL) {
root = pnew;
return;
}
TREE* prnt = root;
do {
if (pnew->viddal == prnt->viddal) {
free(pnew);
return;
}
if (pnew->viddal < prnt->viddal) {
if (prnt->left == NULL) {
prnt->left = pnew;
return;
}
else
prnt = prnt->left;
}
else {
if (prnt->right == NULL) {
prnt->right = pnew;
return;
}
else
prnt = prnt->right;
}
} while (1);
}
void PrintTreeNIZ(TREE* proot)
{
if (proot == NULL)
return;
printf("\n Right Tree");
iterPostorder(proot->right);
printf("\n\n Left Tree");
iterPostorder(proot->left);
printf("\n\n Korin - %d", proot->viddal);
}
void OutputTreeStructure(const char* title)
{
printf("\n\n\n Structur%s:\n\n", title);
ShowLevels();
ShowTree(root, 0);
puts("\n");
}
#define TAB 7
void ShowTree(TREE* proot, int level)
{
if (proot == NULL) return;
ShowTree(proot->right, level + 1);
printf("\n%*c%d", level * TAB + 10, ' ', proot->viddal);
ShowTree(proot->left, level + 1);
}
void ShowLevels(void)
{
int lev;
printf(" Level: ");
for (lev = 1; lev <= TreeHeight(root); lev++)
printf(" %-*d", 6, lev);
printf("\n\n");
}
int TreeHeight(TREE* proot)
{
int lh, rh;
if (proot == NULL) return 0;
lh = TreeHeight(proot->left);
rh = TreeHeight(proot->right);
return lh > rh ? lh + 1 : rh + 1;
}
void EraseTree(TREE* proot)
{
if (proot == NULL)
return;
EraseTree(proot->left);
EraseTree(proot->right);
free(proot);
}
STACK* createStack() {
Stack* tmp = (Stack*)malloc(sizeof(Stack));
tmp->limit = STACK_INIT_SIZE;
tmp->size = 0;
tmp->data = (TREE**)malloc(tmp->limit * sizeof(TREE*));
return tmp;
}
void freeStack(Stack** s) {
free((*s)->data);
free(*s);
*s = NULL;
}
void push(Stack* s, TREE* item) {
if (s->size >= s->limit) {
s->limit *= 2;
s->data = (TREE**)realloc(s->data, s->limit * sizeof(TREE*));
}
s->data[s->size++] = item;
}
TREE* pop(Stack* s) {
if (s->size == 0) {
exit(7);
}
s->size--;
return s->data[s->size];
}
TREE* peek(Stack* s) {
return s->data[s->size - 1];
}
void iterPostorder(TREE* root) {
Stack* ps = createStack();
TREE* lnp = NULL;
TREE* peekn = NULL;
while (!ps->size == 0 || root != NULL) {
if (root) {
push(ps, root);
root = root->left;
}
else {
peekn = peek(ps);
if (peekn->right && lnp != peekn->right) {
root = peekn->right;
}
else {
pop(ps);
printf("\n\t Visited -> %d", peekn->viddal);
lnp = peekn;
}
}
}
freeStack(&ps);
}
// HELP WITH THAT
//--------------------------------------------------------------------------------------------
void DeleteSomeNodes(void)
{
printf("\n\t Deleting needing nods:\n");
TREE* pfind = (TREE*)malloc(sizeof(TREE));
do {
if (pfind->z >= 7 && pfind->z <= 14) {
DeleteNode(root);
printf(" Number %d was deleted from tree\n", root);
}
} while (1);
puts("\n\n");
}
#define NoSubTree 0
#define LeftSubTree -1
#define RightSubTree 1
#define TwoSubTrees 2
int DeleteNode(TREE* pnew_adr)
{
TREE* proot = root;
int subtr;
if (proot == NULL) return 0;
if (pnew_adr->viddal < proot->viddal)
return DeleteNode(proot->left);
if (pnew_adr->viddal > proot->viddal)
return DeleteNode(proot->right);
if (proot->left == NULL && proot->right == NULL)
subtr = NoSubTree;
else if (proot->left == NULL)
subtr = RightSubTree;
else if (proot->right == NULL)
subtr = LeftSubTree;
else
subtr = TwoSubTrees;
switch (subtr) {
case NoSubTree:
root = NULL; break;
case LeftSubTree:
root = proot->left; break;
case RightSubTree:
root = proot->right; break;
case TwoSubTrees:
TREE* pnew_root = proot->right, * pnew_prnt = proot;
while (pnew_root->left != NULL) {
pnew_prnt = pnew_root;
pnew_root = pnew_root->left;
}
pnew_root->left = proot->left;
if (pnew_root != proot->right) {
pnew_prnt->left = pnew_root->right;
pnew_root->right = proot->right;
}
root = pnew_root;
}
free(proot);
return 1;
}
//--------------------------------------------------------------------------------------------
I am making a Hash Map with people's names as its key using C language. I am using separate chaining to resolve the collision.
This is my code:
#include<stdio.h>
#include<stdlib.h>
#define MinTableSize 1
#include <stdbool.h>
//Colission resolution Using linked list
struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;
typedef unsigned int Index;
Index Hash(const char *Key, int Tablesize)
{
unsigned int HashVal = 0;
while(*Key != '\0')
{
HashVal += *Key++;
}
return HashVal % Tablesize;
}
struct ListNode
{
int Element;
Position Next;
};
typedef Position List;
struct HashTbl
{
int TableSize;
List *TheLists;
};
//Function to find next prime number for the size
bool isPrime(int n)
{
if(n <= 1)
{
return false;
}
if(n <= 3)
{
return true;
}
if(n%2 == 0 || n%3 == 0)
{
return false;
}
for(int i = 5; i*i <= n; i = i + 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int NextPrime(int N)
{
if(N <= 1)
{
return 2;
}
int prime = N;
bool found = false;
while(!found)
{
prime++;
if(isPrime(prime))
{
found = true;
}
}
return prime;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if(TableSize < MinTableSize)
{
printf("Table size is too small\n");
return NULL;
}
H = malloc(sizeof(struct HashTbl));
if(H == NULL)
{
printf("Out of space\n");
return NULL;
}
H->TableSize = NextPrime(TableSize);
H->TheLists = malloc(sizeof(List) * H->TableSize);
if(H->TheLists == NULL)
{
printf("Out of space\n");
return NULL;
}
for(i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = malloc(sizeof(struct ListNode));
if(H->TheLists[i] == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
H->TheLists[i]->Next = NULL;
}
}
return H;
}
//funtion to find the value
Position Find(const char *Key, HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(Key, H->TableSize)];
P = L->Next;
while(P != NULL && P->Element != Key)
{
P = P->Next;
}
return P;
}
void Insert(const char *Key, HashTable H)
{
Position Pos;
Position NewCell;
List L;
Pos = Find(Key, H);
if(Pos == NULL)
{
NewCell = malloc(sizeof(struct ListNode));
if(NewCell == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Next;
NewCell->Element = Key;
L->Next = NewCell;
printf("Key inserted\n");
}
}
else
{
printf("Key already exist\n");
}
}
int main()
{
char Name[6][20] = {"Joshua", "Erica", "Elizabeth", "Monica", "Jefferson", "Andrian"};
int Size = sizeof(Name[0])/sizeof(Name[0][0]);
HashTable H = InitializeTable(Size);
Insert(Name[0], H);
Insert(Name[1], H);
Insert(Name[2], H);
Insert(Name[3], H);
}
The putout of this code is:
Key inserted
Key inserted
This means, it only successfully inserted two keys, while the other name has not been inserted. I think there's some error in my Insert() function, but I got no clue. I tried using an online compiler and it compile properly.
I get a pointer with 0xCDCDCDCD when I want to print a tree but no problem when I want to print a queue in the almost same code
I write a queue by a c program and revise it to print as a tree , that queue was successful printed but when I tried to print the tree my visual studio told me there was a 0xCDCDCDCD problem.
this is the previous version that ran well.
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
long long value;
//int value
struct _node *next;
}Node;
typedef struct _Queue
{
Node *head;
Node *tail;
}Queue;
Queue* init_queue()
{
Queue *queue=(Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = NULL;
return queue;
}
void enQueue(Queue *pQueue,Node *pNode)
{
if(pQueue->head == NULL)
{//when it's empty
pQueue->head = pNode;
pQueue->tail = pNode;
}
else
{
pQueue->tail->next = pNode;
pQueue->tail = pNode;
}
}
int deQueue(Queue *pQueue)
{
int i;
if(pQueue->head == NULL)
{
return NULL;
}
// Node *deNode;
//Node *tmp;
//Node *deNode;
//deNode= pQueue->head;
Node *deNode= pQueue->head;
//Node *tmp= pQueue->head;
i=deNode->value;
pQueue->head= pQueue->head->next;
//free(deNode);
return i;
}
Node* init_node(int value)
{
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->value=value;
return new_node;
}
//0:empty
int ifEmpty(Queue *pQueue)
{
if(pQueue->head == NULL)
{
printf("empty tree\n");
return 0;
}
printf("queue is not empty\n");
return 1;
}
int main()
{
Queue *queue=init_queue();
int i;
ifEmpty(queue);
printf("insert node to queue\n");
for(i=0; i<7;i++)
{
Node *node = init_node(i);
enQueue(queue,node);
// free(node);
}
// Node *node = init_node(1);
// printf("node->value = %d\n",node->value);
// enQueue(queue,node);
ifEmpty(queue);
for(i=0;i<7;i++)
{
int deNode = deQueue(queue);
//if(!deNode)
//{
//printf("NULL\n");
//}
//else
//{
printf("deNode->value = %d\n",deNode);
//}
}
//int deNode = deQueue(queue);
//free(queue);
// printf("\n after free deNode->value = %d\n",queue->head->value);
ifEmpty(queue);
return 0;
}
I want to change this into a tree format but my visual studio told me there was a 0xCDCDCDCD problem. below are my codecs:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define NUM 6
typedef struct _node
{
int value;
struct _node *left;
struct _node *right;
}TNode,*Tree;
//add a *next in q_node is my purpose
//other wise , we need to add in the Tree node struct
//So, for the sake of doesn't modify the struct of tree
//I design a q_node struct to include it
//we can use define command to make it as a template.
typedef struct _q_node
{
TNode *t_node;
int depth;
int blank; //0: means correspoinding tree node is not NULL(default)
struct _q_node *next;
}QNode;
typedef struct _Queue
{
QNode *head;
QNode *tail;
}Queue;
Queue* init_queue()
{
Queue *queue=(Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = NULL;
return queue;
}
int enQueue(Queue *pQueue,TNode *pTNode,int pDepth)
{
QNode *pQNode = (QNode *)malloc(sizeof(QNode));
pQNode->depth = pDepth;
pQNode->blank = 0; //default config
if(pTNode==NULL)
{
//change default setting; 1 means it's blank QNode
pQNode->blank =1;
}
pQNode->t_node= pTNode;
if(pQueue->head == NULL)
{//when it's empty
pQueue->head = pQNode;
pQueue->tail = pQNode;
}
else
{
pQueue->tail->next = pQNode;
pQueue->tail = pQNode;
}
}
QNode* deQueue(Queue *pQueue)
{
if(pQueue->head == NULL)
{
return NULL;
}
QNode *deNode= pQueue->head;
pQueue->head = pQueue->head->next;
//pQueue->head = pQueue->head->next;
//deNode = deNode->next;
return deNode;
}
TNode* init_TNode(int value)
{
TNode *new_node = (TNode*)malloc(sizeof(TNode));
new_node->value=value;
new_node->left = new_node->right = NULL;
return new_node;
}
//0:empty
int ifEmpty(Queue *pQueue)
{
if(pQueue->head == NULL)
{
//printf("empty tree\n");
return 0;
}
//printf("queue is not empty\n");
return 1;
}
int insert_tree(Tree pTree,int pValue)
{
//found NULL sub tree, then add to his father->left
if(!pTree)
{
return 0;
}
TNode *tNode = init_TNode(pValue);
if(tNode==NULL)
{
printf("create TNode error!\n");
return 0;
}
if(pValue < pTree->value)
if(insert_tree(pTree->left,pValue)==0)
{
//no left child any more,set a new left child to pTree
pTree->left = tNode;
printf("insert :%d\n",pValue);
}
if(pValue > pTree->value)
if(insert_tree(pTree->right,pValue)==0)
{
pTree->right = tNode;
printf("insert :%d\n",pValue);
}
}
Tree creatTree(int num)
{
srand(time(NULL));
Tree root = init_TNode(rand()%100);
printf("root is %d\n",root->value);
int i ;
for(i=1;i<num;i++)
{
insert_tree(root,rand()%100);
}
printf("creat tree succuess!Tree heigh is:%d\n",get_tree_height(root));
return root ;
}
int get_tree_height(Tree pRoot)
{
if(!pRoot)
{
return 0;
}
int lh=0,rh=0;
lh = get_tree_height(pRoot->left);
rh = get_tree_height(pRoot->right);
return (lh<rh)?(rh+1):(lh+1);
}
int breath_travel(Tree pRoot,Queue *pQueue)
{
int height = get_tree_height(pRoot);
int pad_num = 3;
//compare to the node's depth in the "while loop"
int current_depth = 1;
if(!pRoot)
{
return 0;
}
enQueue(pQueue,pRoot,1);
printf("_______________________\n");
printf("breath begin,enter root:\n");
while(ifEmpty(pQueue)!=0)
{
QNode *qNode = deQueue(pQueue);
//the sub node's depth is 1 more then the parent's
int child_depth = qNode->depth + 1 ;
if(qNode->depth > current_depth)
{
current_depth = qNode->depth;
printf("\n\n");
}
// ***************0**************** pad_between = 31 ; pad_front = 15 (depth == 1)
// *******0***************0******** pad_between = 15 ; pad_front = 7 (depth == 2)
// ***0*******0*******0*******0**** pad_between = 7 ; pad_front = 3 (depth == 3)
// *0***0***0***0***0***0***0***0** pad_between = 3 ; pad_front = 1 (depth == 4)
// 0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0* pad_between = 1 ; pad_front = 0; (depth == 5)
// Tree height = 5
// pad_num = 1
// padding between node = (1+2*pad_front)*pad_num = (1+ (1<<(height-depth))-1)*pad_num
// (1<< (height - current_depth))-1=2^(height - current_depth)-1
int pad_front = (1<< (height - current_depth))-1;
if((qNode->blank == 1))
{
//add the parent node's padding:2
if(pad_front == 0) printf("%*s%*s",pad_num,"o",pad_num," ");
else printf("%*s%*s%*s",pad_front*pad_num," ",pad_num,"o",(1+pad_front)*pad_num," ");
//pad_front*pad_num+(1+pad_front)*pad_num=(1+2*pad_front)*pad_num=padding between node
if(child_depth <= height)
{
//enter two NULL sub-tree node.
//every time you enter NULL TNode,there's corresponding blank QNode.
enQueue(pQueue,NULL,child_depth);
enQueue(pQueue,NULL,child_depth);
}
}
else
{
if(pad_front == 0) printf("%*d%*s",pad_num,qNode->t_node->value,pad_num," ");
else printf("%*s%*d%*s",pad_front*pad_num," ",pad_num,qNode->t_node->value,(1+pad_front)*pad_num," ");
if(child_depth <=height)
{
enQueue(pQueue,qNode->t_node->left,child_depth);
enQueue(pQueue,qNode->t_node->right,child_depth);
}
}
} //while end
printf("\n-----------\nbreath end!\n-----------\n");
return 1;
}
int main(int argc,char **argv)
{
Queue *queue=init_queue();
int i;
ifEmpty(queue);
printf("insert node to queue\n");
int num = NUM; //default
if(argc == 2)
{
num = atoi(argv[1]);
}
Tree root = creatTree(num);
if(!root)
{
printf("create Tree failed!\n");
return 0;
}
breath_travel(root,queue);
return 0;
}
the problem is in the deQueue function when I want to print the tree my visual studio told me " pQueue->head= pQueue->head->next;" this line had a 0xCDCDCDCD
problem in the deQueue function I don't know why I even tried to put all this funtion in the main function but the problem was still there:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define NUM 6
typedef struct _node
{
int value;
struct _node *left;
struct _node *right;
}TNode, *Tree;
//add a *next in q_node is my purpose
//other wise , we need to add in the Tree node struct
//So, for the sake of doesn't modify the struct of tree
//I design a q_node struct to include it
//we can use define command to make it as a template.
typedef struct _q_node
{
TNode *t_node;
int depth;
int blank; //0: means correspoinding tree node is not NULL(default)
struct _q_node *next;
}QNode;
typedef struct _Queue
{
QNode *head;
QNode *tail;
}Queue;
Queue* init_queue()
{
Queue *queue = (Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = NULL;
return queue;
}
int enQueue(Queue *pQueue, TNode *pTNode, int pDepth)
{
QNode *pQNode = (QNode *)malloc(sizeof(QNode));
pQNode->depth = pDepth;
pQNode->blank = 0; //default config
if (pTNode == NULL)
{
//change default setting; 1 means it's blank QNode
pQNode->blank = 1;
}
pQNode->t_node = pTNode;
if (pQueue->head == NULL)
{//when it's empty
pQueue->head = pQNode;
pQueue->tail = pQNode;
}
else
{
pQueue->tail->next = pQNode;
pQueue->tail = pQNode;
}
}
/*QNode* deQueue(Queue *pQueue)
{
if (pQueue->head == NULL)
{
return NULL;
}
QNode *deNode = pQueue->head;
pQueue->head = pQueue->head->next;
//pQueue->head = pQueue->head->next;
//deNode = deNode->next;
return deNode;
}
*/
TNode* init_TNode(int value)
{
TNode *new_node = (TNode*)malloc(sizeof(TNode));
new_node->value = value;
new_node->left = new_node->right = NULL;
return new_node;
}
//0:empty
int ifEmpty(Queue *pQueue)
{
if (pQueue->head == NULL)
{
//printf("empty tree\n");
return 0;
}
//printf("queue is not empty\n");
return 1;
}
int insert_tree(Tree pTree, int pValue)
{
//found NULL sub tree, then add to his father->left
if (!pTree)
{
return 0;
}
TNode *tNode = init_TNode(pValue);
if (tNode == NULL)
{
printf("create TNode error!\n");
return 0;
}
if (pValue < pTree->value)
if (insert_tree(pTree->left, pValue) == 0)
{
//no left child any more,set a new left child to pTree
pTree->left = tNode;
printf("insert :%d\n", pValue);
}
if (pValue > pTree->value)
if (insert_tree(pTree->right, pValue) == 0)
{
pTree->right = tNode;
printf("insert :%d\n", pValue);
}
}
Tree creatTree(int num)
{
srand((unsigned)time(NULL));
Tree root = init_TNode(rand() % 100);
printf("root is %d\n", root->value);
int i;
for (i = 1; i < num; i++)
{
insert_tree(root, rand() % 100);
}
printf("creat tree succuess!Tree heigh is:%d\n", get_tree_height(root));
return root;
}
int get_tree_height(Tree pRoot)
{
if (!pRoot)
{
return 0;
}
int lh = 0, rh = 0;
lh = get_tree_height(pRoot->left);
rh = get_tree_height(pRoot->right);
return (lh < rh) ? (rh + 1) : (lh + 1);
}
/*
int breath_travel(Tree pRoot, Queue *pQueue)
{
int height = get_tree_height(pRoot);
int pad_num = 3;
//compare to the node's depth in the "while loop"
int current_depth = 1;
if (!pRoot)
{
return 0;
}
enQueue(pQueue, pRoot, 1);
printf("_______________________\n");
printf("breath begin,enter root:\n");
while (ifEmpty(pQueue) != 0)
{
//QNode *qNode = deQueue(pQueue);
//the sub node's depth is 1 more then the parent's
if (pQueue->head == NULL)
{
return NULL;
}
QNode *qNode = pQueue->head;
pQueue->head = pQueue->head->next;
int child_depth = qNode->depth + 1;
if (qNode->depth > current_depth)
{
current_depth = qNode->depth;
printf("\n\n");
}
// ***************0**************** pad_between = 31 ; pad_front = 15 (depth == 1) 一共31个*
// *******0***************0******** pad_between = 15 ; pad_front = 7 (depth == 2)
// ***0*******0*******0*******0**** pad_between = 7 ; pad_front = 3 (depth == 3)
// *0***0***0***0***0***0***0***0** pad_between = 3 ; pad_front = 1 (depth == 4)
// 0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0* pad_between = 1 ; pad_front = 0; (depth == 5)
// Tree height = 5
// pad_num = 1
// padding between node = (1+2*pad_front)*pad_num = (1+ (1<<(height-depth))-1)*pad_num
// (1<< (height - current_depth))-1=2^(height - current_depth)-1
int pad_front = (1 << (height - current_depth)) - 1;
if ((qNode->blank == 1))
{
//add the parent node's padding:2
if (pad_front == 0) printf("%*s%*s", pad_num, "o", pad_num, " ");
else printf("%*s%*s%*s", pad_front*pad_num, " ", pad_num, "o", (1 + pad_front)*pad_num, " ");
//pad_front*pad_num+(1+pad_front)*pad_num=(1+2*pad_front)*pad_num=padding between node
if (child_depth <= height)
{
//enter two NULL sub-tree node.
//every time you enter NULL TNode,there's corresponding blank QNode.
enQueue(pQueue, NULL, child_depth);
enQueue(pQueue, NULL, child_depth);
}
}
else
{
if (pad_front == 0) printf("%*d%*s", pad_num, qNode->t_node->value, pad_num, " ");
else printf("%*s%*d%*s", pad_front*pad_num, " ", pad_num, qNode->t_node->value, (1 + pad_front)*pad_num, " ");
if (child_depth <= height)
{
enQueue(pQueue, qNode->t_node->left, child_depth);
enQueue(pQueue, qNode->t_node->right, child_depth);
}
}
} //while end
printf("\n-----------\nbreath end!\n-----------\n");
return 1;
}
*/
int main(int argc, char **argv)
{
Queue *pQueue = init_queue();
int i;
ifEmpty(pQueue);
printf("insert node to queue\n");
int num = NUM; //default
if (argc == 2)
{
num = atoi(argv[1]);
}
Tree pRoot = creatTree(num);
if (!pRoot)
{
printf("create Tree failed!\n");
return 0;
}
//breath_travel(root, queue);
int height = get_tree_height(pRoot);
int pad_num = 3;
//compare to the node's depth in the "while loop"
int current_depth = 1;
if (!pRoot)
{
return 0;
}
enQueue(pQueue, pRoot, 1);
printf("_______________________\n");
printf("breath begin,enter root:\n");
while (ifEmpty(pQueue) != 0)
{
//QNode *qNode = deQueue(pQueue);
//the sub node's depth is 1 more then the parent's
if (pQueue->head == NULL)
{
return NULL;
}
QNode *qNode = pQueue->head;
pQueue->head = pQueue->head->next;
int child_depth = qNode->depth + 1;
if (qNode->depth > current_depth)
{
current_depth = qNode->depth;
printf("\n\n");
}
// ***************0**************** pad_between = 31 ; pad_front = 15 (depth == 1)
// *******0***************0******** pad_between = 15 ; pad_front = 7 (depth == 2)
// ***0*******0*******0*******0**** pad_between = 7 ; pad_front = 3 (depth == 3)
// *0***0***0***0***0***0***0***0** pad_between = 3 ; pad_front = 1 (depth == 4)
// 0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0* pad_between = 1 ; pad_front = 0; (depth == 5)
// Tree height = 5
// pad_num = 1
// padding between node = (1+2*pad_front)*pad_num = (1+ (1<<(height-depth))-1)*pad_num
// (1<< (height - current_depth))-1=2^(height - current_depth)-1
int pad_front = (1 << (height - current_depth)) - 1;
if ((qNode->blank == 1))
{
//add the parent node's padding:2
if (pad_front == 0) printf("%*s%*s", pad_num, "o", pad_num, " ");
else printf("%*s%*s%*s", pad_front*pad_num, " ", pad_num, "o", (1 + pad_front)*pad_num, " ");
//pad_front*pad_num+(1+pad_front)*pad_num=(1+2*pad_front)*pad_num=padding between node
if (child_depth <= height)
{
//enter two NULL sub-tree node.
//every time you enter NULL TNode,there's corresponding blank QNode.
enQueue(pQueue, NULL, child_depth);
enQueue(pQueue, NULL, child_depth);
}
}
else
{
if (pad_front == 0) printf("%*d%*s", pad_num, qNode->t_node->value, pad_num, " ");
else printf("%*s%*d%*s", pad_front*pad_num, " ", pad_num, qNode->t_node->value, (1 + pad_front)*pad_num, " ");
if (child_depth <= height)
{
enQueue(pQueue, qNode->t_node->left, child_depth);
enQueue(pQueue, qNode->t_node->right, child_depth);
}
}
} //while end
printf("\n-----------\nbreath end!\n-----------\n");
return 0;
}
I am trying to solve this question-
Given an array A of unsigned 32-bit ints, choose two in-bounds indices i, j so as to maximize the value of A[i] ^ A[j], where ^ is the bitwise XOR (exclusive OR) operator.
Example Input:
4 2 0 13 49
Output:
60
Explanation: 13 ^ 49 is 60
Here is my code
#include <stdio.h>
void insert(int n, int pos, struct node *t);
int find(struct node *p1, struct node *p2);
struct node *alloc();
struct node{
int value;
struct node *left;
struct node *right;
};
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n;
scanf("%d", &n);
struct node root;
root.value = 0;
root.left = root.right = NULL;
while (n--)
{
int num;
scanf("%d", &num);
insert(num, 31 , &root);
}
int max = find(&root, &root);
printf("%d\n", max);
}
return 0;
}
void insert(int n, int pos, struct node *t)
{
if (pos >= 0)
{
struct node *m;
int bit = (1 << pos)&n;
if (bit)
{
if (t->right == NULL)
{
m=alloc();
m->value = 1;
m->left = NULL;
m->right = NULL;
t->right = m;
}
if (pos == 0)
{
m=alloc();
m->value = n;
m->left = NULL;
m->right = NULL;
t->left = m;
}
insert(n, pos - 1, t->right);
}
else
{
if (t->left == NULL)
{
m = alloc();
m->value = 0;
m->left = NULL;
m->right = NULL;
t->left = m;
}
if (pos == 0)
{
m=alloc();
m->value = n;
m->left = NULL;
m->right = NULL;
t->left = m;
}
insert(n, pos - 1, t->left);
}
}
}
int find(struct node *p1, struct node *p2)
{
if ((p1->left != NULL) ||(p1->right != NULL))
{
int n01 = 0;
int n10 = 0;
if (p1->left != NULL && p2->right != NULL)
{
n01 = find(p1->left, p2->right);
}
if ((p1->right != NULL) && (p2->left != NULL))
{
n10 = find(p2->left, p1->right);
}
else
{
if (p1->left!=NULL && p2->left!=NULL)
n01 = find(p1->left, p2->left);
else
n10 = find(p1->right, p2->right);
}
return (n01 > n10 ? n01 : n10);
}
else
{
return p1->value^p2->value;
}
}
struct node *alloc()
{
return (struct node *) malloc(sizeof(struct node));
}
I am only getting a 0 as output.I know there are mistakes in my code.Please help me in finding the mistakes or if necessary the right solution.