How can I increment a counter in a binary search tree? - c

I have a list of numbers in a bst and I need to count how many times the program has the access to every single number and print it
enter
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define HASHSIZE 153
typedef struct tree
{
int key;
int count;
struct tree *dx;
struct tree *sx;
struct tree *parent;
} node;
int Insertion(node **T, node *z)
{
node* y = NULL;
node* x = *T;
// int i=1;
while ( x != NULL )
{
y = x;
if ( z->key < x->key)
{
x = x->sx;
// x->count=i; I DON'T KNOW HERE
} else if ( z->key > x->key)
{
x = x->dx;
} else
{
return -1;
}
}
z->parent = y;
if ( y == NULL ) *T = z;
if ( (y != NULL) && (z->key < y->key) ) y->sx = z;
if ( (y != NULL) && (z->key > y->key) ) y->dx = z;
return 0;
}
int main(void)
{
FILE *fp;
fp = fopen("data.txt","r");
node *x = NULL;
int search;
hashtable = (hash *) malloc(HASHSIZE * sizeof(hash));
for (i = 0; i<HASHSIZE; i++) hashtable[i].head = NULL;
while (!feof(fp))
{
fscanf(fp, "%d\t", search);
if ( Search(hashtable[H(search)].head, search)==NULL )
{
x = NewNode(search);
Insertion( &hashtable[H(x->key)].head, x);
}
}
//Here there's also the node elimination but it's not important right now
fclose(fp);
return 0;
}
My problem is printing the number of times that a number compare in a file.
I put down there NewNode, Search and H function
// HASH //
typedef struct _hash
{
node *head;
} hash;
hash *hashtable = NULL;
int H(int key)
{
return (key % HASHSIZE);
}
// NEWNODE //
node* NewNode(int z)
{
node* temp;
temp = (node*) malloc( sizeof(node) );
temp->key = z;
temp->sx = NULL;
temp->dx = NULL;
temp->parent = NULL;
return temp;
}
// SEARCH //
node* Search(node *x, int k)
{
while ( (x != NULL) && (k != x->key) )
{
if ( k < x->key )
{
x = x->sx;
}
else
{
x = x->dx;
}
}
return x;
}
// TOP //
int Top(int a, int b)
{
if (a>b) return a;
return b;
}
// MIN //
node* Min(node *x)
{
while (x->sx != NULL) x = x->sx;
return x;
}
// MAX //
node* Max(node *x)
{
while (x->dx != NULL) x = x->dx;
return x;
}
// NEXT //
node* Next(node *x)
{
if (x->dx != NULL)
return Min(x->dx);
node *y = x->parent;
while ( y != NULL && x == y->dx ){
x = y;
y = y->parent;
}
return y;
}
// HEIGHT //
int Height(node *x)
{
if (x == NULL)
return 0;
return( 1 + Top( Height(x->sx), Height(x->dx) ));
}
// DECANT //
void Decant(node **T, node *u, node *v)
{
if ( u->parent == NULL)
*T = v;
if ( u->parent != NULL && u == u->parent->sx )
u->parent->sx = v;
if ( u->parent != NULL && u == u->parent->dx )
u->parent->dx = v;
if ( v != NULL)
v->parent = u->parent;
}
// DELATE //
void Delate(node **T, node *z)
{
node *y;
if ( z->sx == NULL )
Decant(T, z, z->dx);
if ( (z->sx != NULL) && (z->dx == NULL) )
Decant(T, z, z->sx);
if ( (z->sx != NULL) && (z->dx != NULL) )
{
y = Min(z->dx);
if (y->parent != z){
Decant(T, y, y->dx);
y->dx = z->dx;
y->dx->parent = y;
}
Decant(T, z, y);
y->sx = z->sx;
y->sx->parent = y;
}
free(z);
}
Thx everyone!

Related

How to remove necessary nodes from a binary tree?

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;
}
//--------------------------------------------------------------------------------------------

Why is my Hash Map insert function not working?

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 have a problem with swap code in Doubly linked list

I made swap code in C
but I didn't get perfect grade in school compiler.
I think there is a problem with following code.
I made doubly linked list with struct and pointer.
Node is defined that:
struct node* newnode(char x)
{
struct node* new = (struct node*)malloc(sizeof(struct node));
new->next = NULL;
new->prev = NULL;
new->c = x;
return new;
}
And the following code is swap code that I made each function factor mean that "struct node*p" is full list from head to tail, "int a and b" is rank of list
and "count1(p)" is function that count node in full list and return number of node (exclude head and tail).
void swap(struct node* p, int a, int b)
{
int x, y;
struct node* x1, * x2, emp = { 0 };
int i = 0;
x1 = p;
x2 = p;
if (a >= b) {
x = b;
y = a;
}
else {
x = a;
y = b;
}
if (b <= 0 || a <= 0 || a > N || a > count1(p) || b > N || b > count1(p)) {
printf("invalid position\n");
return;
}while (i < x && x1 != tail) {
x1 = x1->next;
i++;
}
i = 0;
while (i < y && p != tail) {
x2 = x2->next;
i++;
}
if (x1->next != x2)
{
x1->prev->next = x2;
x1->next->prev = x2;
x2->prev->next = x1;
x2->next->prev = x1;
emp.next = x1->next;
emp.prev = x1->prev;
x1->next = x2->next;
x1->prev = x2->prev;
x2->next = emp.next;
x2->prev = emp.prev;
}
if (x1->next == x2)
{
emp.prev = x1->prev;
emp.next = x1->next;
x1->prev->next = x2;
x2->next->prev = x1;
x1->prev = x2;
x1->next = x2->next;
x2->prev = emp.prev;
x2->next = x1;
}
}
The following code is my full code:
#include<stdio.h>
#include<stdlib.h>
int N;
struct node {
struct node* next;
struct node* prev;
char c;
};
struct node* head, * tail;
void reset() {
head = (struct node*)malloc(sizeof(struct node));
tail = (struct node*)malloc(sizeof(struct node));
head->prev = NULL;
head->next = tail;
head->c = NULL;
tail->prev = head;
tail->next = NULL;
tail->c = NULL;
}
struct node* newnode(char x)
{
struct node* new = (struct node*)malloc(sizeof(struct node));
new->next = NULL;
new->prev = NULL;
new->c = x;
return new;
}
void prcount(struct node* p)
{
printf("%d\n", count1(p));
}
int count1(struct node* p)
{
int sum = 0;
while (p != tail) {
p = p->next;
sum++;
}
return sum + -1;
}
void add1(struct node* p, int n, char x)
{
struct node* new1 = newnode(x);
int i = 1;
if (n <= 0 || n > N || n > count1(p) + 1) {
printf("invalid position\n");
return;
}
while (i < n && p != tail) {
p = p->next;
i++;
}
p->next->prev = new1;
new1->prev = p;
new1->next = p->next;
p->next = new1;
}
void delete1(struct node* p, int n)
{
int i = 0;
if (n <= 0 || n > N || n > count1(p)) {
printf("invalid position\n");
return;
}
while (i < n && p != tail)
{
p = p->next;
i++;
}
p->prev->next = p->next;
p->next->prev = p->prev;
free(p);
}
void get1(struct node* p, int n) {
int i = 0;
if (n <= 0 || n > N || n > count1(p)) {
printf("invalid position\n");
return;
}while (i < n && p != tail) {
p = p->next;
i++;
}
printf("%c\n", p->c);
}
void print1(struct node* p)
{
int i = 0;
if (count1(p) == 0) {
printf("invalid position\n");
return;
}
while (i < N && p->next != tail)
{
p = p->next;
printf("%c", p->c);
i++;
}
printf("\n");
}void removeall(struct node* p)
{
struct node* emp;
p = p->next;
while (p != tail)
{
emp = p->next;
free(p);
p = emp;
}
head->prev = NULL;
head->next = tail;
head->c = NULL;
tail->prev = head;
tail->next = NULL;
tail->c = NULL;
}
void swap(struct node* p, int a, int b)
{
int x, y;
struct node* x1, * x2, emp = { 0 };
int i = 0;
x1 = p;
x2 = p;
if (a >= b) {
x = b;
y = a;
}
else {
x = a;
y = b;
}
if (b <= 0 || a <= 0 || a > N || a > count1(p) || b > N || b > count1(p)) {
printf("invalid position\n");
return;
}while (i < x && x1 != tail) {
x1 = x1->next;
i++;
}
i = 0;
while (i < y && x2 != tail) {
x2 = x2->next;
i++;
}
if (x1->next != x2)
{
x1->prev->next = x2;
x1->next->prev = x2;
x2->prev->next = x1;
x2->next->prev = x1;
emp.next = x1->next;
emp.prev = x1->prev;
x1->next = x2->next;
x1->prev = x2->prev;
x2->next = emp.next;
x2->prev = emp.prev;
}
if (x1->next == x2)
{
emp.prev = x1->prev;
emp.next = x1->next;
x1->prev->next = x2;
x2->next->prev = x1;
x1->prev = x2;
x1->next = x2->next;
x2->prev = emp.prev;
x2->next = x1;
}
}
int main()
{
int i;
int r, n;
char x, y;
reset();
scanf("%d", &N);
for (i = 0; i < N; i++)
{
scanf(" %c", &x);
if (x == 'A') {//A mean add(head,int a, char x) -> add 'x' on a rank in list
scanf("%d", &r);
scanf(" %c", &y);
add1(head, r, y);
}
else if (x == 'D') {// D mean delete(struct node *head, int a) -> delete element on int a rank
scanf("%d", &r);
delete1(head, r);
}
else if (x == 'G') {//G mean Get(head,int a)-> print element on int a rank
scanf("%d", &r);
get1(head, r);
}
else if (x == 'P') {//P mean print(head) -> print all element in list
print1(head);
}
else if (x == 'R') {//R mean Removeall(head) -> remove all node (exclude head and tail0
removeall(head);
}
else if (x == 'C')//C Mean prcount(head) -> count and print number of node in list (exclude head and tail)
{
prcount(head);
}
else if (x == 'S') {//S mean Swap(head, int a, int b) -> swap element of int a rank with int b rank
scanf("%d", &r);
scanf("%d", &n);
swap(head, r, n);
}
}
removeall(head);
}
It's my full code.
I want to know is there any problem Or more effective way to make swap code?
#include<stdio.h>
#include<stdlib.h>
int N;
struct node {
struct node* next;
struct node* prev;
char c;
};
struct node* head, * tail;
void reset() {
head = (struct node*)malloc(sizeof(struct node));
tail = (struct node*)malloc(sizeof(struct node));
head->prev = NULL;
head->next = tail;
head->c = NULL;
tail->prev = head;
tail->next = NULL;
tail->c = NULL;
}
struct node* newnode(char x)
{
struct node* new = (struct node*)malloc(sizeof(struct node));
new->next = NULL;
new->prev = NULL;
new->c = x;
return new;
}
void prcount(struct node* p)
{
printf("%d\n", count1(p));
}
int count1(struct node* p)
{
int sum = 0;
while (p != tail) {
p = p->next;
sum++;
}
return sum + -1;
}
void add1(struct node* p, int n, char x)
{
struct node * new1 = newnode(x);
int i = 1;
if (n<=0||n > N || n > count1(p) + 1) {
printf("invalid position\n");
return;
}
while (i < n && p != tail) {
p = p->next;
i++;
}
p->next->prev = new1;
new1->prev = p;
new1->next = p->next;
p->next = new1;
}
void delete1(struct node* p, int n)
{
int i = 0;
if (n <= 0 || n > N || n > count1(p)) {
printf("invalid position\n");
return;
}
while (i < n && p != tail)
{
p = p->next;
i++;
}
p->prev->next = p->next;
p->next->prev = p->prev;
free(p);
}
void get1(struct node* p, int n) {
int i = 0;
if (n <= 0 || n > N || n > count1(p)) {
printf("invalid position\n");
return;
}while (i < n && p != tail) {
p = p->next;
i++;
}
printf("%c\n", p->c);
}
void print1(struct node* p)
{
int i = 0;
if (count1(p) == 0) {
printf("invalid position\n");
return;
}
while (i < N && p->next != tail)
{
p = p->next;
printf("%c", p->c);
i++;
}
printf("\n");
}void removeall(struct node* p)
{
struct node* emp;
p = p->next;
while (p != tail)
{
emp = p->next;
free(p);
p = emp;
}
head->prev = NULL;
head->next = tail;
head->c = NULL;
tail->prev = head;
tail->next = NULL;
tail->c = NULL;
}
void swap(struct node* p, int a, int b)
{
int x, y;
struct node* x1, * x2, emp = { 0 };
int i = 0;
x1 = p;
x2 = p;
if (a >= b) {
x = b;
y = a;
}
else {
x = a;
y = b;
}
if (b <= 0 || a <= 0 || a > N || a > count1(p) || b > N || b > count1(p)) {
printf("invalid position\n");
return;
}while (i < x && x1 != tail) {
x1 = x1->next;
i++;
}
i = 0;
while (i < y && p != tail) {
x2 = x2->next;
i++;
}
if (x1->next != x2)
{
x1->prev->next = x2;
x1->next->prev = x2;
x2->prev->next = x1;
x2->next->prev = x1;
emp.next = x1->next;
emp.prev = x1->prev;
x1->next = x2->next;
x1->prev = x2->prev;
x2->next = emp.next;
x2->prev = emp.prev;
}
if (x1->next == x2)
{
emp.prev = x1->prev;
emp.next = x1->next;
x1->prev->next = x2;
x2->next->prev = x1;
x1->prev = x2;
x1->next = x2->next;
x2->prev = emp.prev;
x2->next = x1;
}
}
int main()
{
int i;
int r, n;
char x, y;
reset();
scanf("%d", &N);
for (i = 0; i < N; i++)
{
scanf(" %c", &x);
if (x == 'A') {
scanf("%d", &r);
scanf(" %c", &y);
add1(head, r, y);
}
else if (x == 'D') {
scanf("%d", &r);
delete1(head, r);
}
else if (x == 'G') {
scanf("%d", &r);
get1(head, r);
}
else if (x == 'P') {
print1(head);
}
else if (x == 'R') {
removeall(head);
}
else if (x == 'C')
{
prcount(head);
}
else if (x == 'S') {
scanf("%d", &r);
scanf("%d", &n);
swap(head, r, n);
}
}
removeall(head);
}
it is my full code
int N is used as the number of input commands in main. The comparisons with N in your list functions (as if N would denote the number of nodes) make no sense - you could just drop them.
Besides that, there are some places where a compiler with appropriate options would issue warnings - perhaps that's why you didnt get perfect grade in school compiler.
head->c = NULL;
Since c is of type char and NULL is a null pointer constant this doesn't fit; change to
head->c = '\0'; // or head->c = 0;
printf("%d\n", count1(p));
There you call count1 before it is declared. Declare it before use with
int count1(struct node* p);
or move the function definition before the first function using it.

Deleting the root of a heap with no effect

I have tried to implement functions related to heaps in C and I have stumbled across a problem with my delete heap root function.
When the heap has only one element, the function does not delete anything, even though I explicitly said that the heap becomes NULL if it has only one element.
Below I have posted my code with all the functions that I have created (maybe there is something wrong with the other functions, but it doesn't seem likely to me). The main problem is the deleteRoot function.
#include <stdio.h>
#include <stdlib.h>
typedef struct Heap Heap;
struct Heap
{
Heap *left;
Heap *right;
Heap *parent;
int value;
};
Heap *newHeap(int x)
{
Heap *t = malloc(sizeof(Heap));
t->value = x;
t->left = NULL;
t->right = NULL;
t->parent = NULL;
return t;
}
void printHeap(Heap *h)
{
if(h!=NULL)
{
printf("Value %d (",h->value);
printHeap(h->left);
printf(")");
printf("(");
printHeap(h->right);
printf(")");
}
}
int getHeapMinDepth(Heap *h)
{
if(h == NULL) return 0;
int leftdepth = getHeapMinDepth(h->left);
int rightdepth = getHeapMinDepth(h->right);
int mindepth = (leftdepth < rightdepth) ? leftdepth : rightdepth;
return mindepth + 1;
}
int getHeapMaxDepth(Heap *h)
{
if(h == NULL) return 0;
int leftdepth = getHeapMaxDepth(h->left);
int rightdepth = getHeapMaxDepth(h->right);
int maxdepth = (leftdepth > rightdepth) ? leftdepth : rightdepth;
return maxdepth + 1;
}
void bubbleUp(Heap *h)
{
int aux;
if(h->parent != NULL && h != NULL)
{
if(h->parent->value < h->value)
{
aux = h->value;
h->value = h->parent->value;
h->parent->value = aux;
bubbleUp(h->parent);
}
}
}
void bubbleDown(Heap *h)
{
int aux;
if(h != NULL)
{
if(h->left != NULL && h->left->value > h->value)
{
aux = h->value;
h->value = h->left->value;
h->left->value = aux;
bubbleDown(h->left);
}
else if(h->right != NULL && h->right->value > h->value)
{
aux = h->value;
h->value = h->right->value;
h->right->value = aux;
bubbleDown(h->right);
}
}
}
void addElement(Heap *h ,int x)
{
if(h == NULL) h = newHeap(x);
else if(h->left == NULL)
{
h->left = newHeap(x);
h->left->parent = h;
bubbleUp(h->left);
}
else if(h->right == NULL)
{
h->right = newHeap(x);
h->right->parent = h;
bubbleUp(h->right);
}
else if(getHeapMinDepth(h->left) <= getHeapMinDepth(h->right)) addElement(h->left,x);
else addElement(h->right,x);
}
void deleteRoot(Heap *h)
{
Heap *auxheap = h;
if(h!=NULL && h->left == NULL && h->right == NULL) h = NULL;
else if(h!=NULL)
{
while(auxheap ->left != NULL || auxheap->right != NULL)
{
if(getHeapMaxDepth(auxheap->left) > getHeapMaxDepth(auxheap->right)) auxheap = auxheap->left;
else auxheap = auxheap->right;
}
h->value = auxheap->value;
auxheap->value = -1;
auxheap = auxheap->parent;
if(auxheap->right != NULL && auxheap->right->value == -1) auxheap->right = NULL;
else auxheap->left = NULL;
bubbleDown(h);
}
}
int main()
{
int i;
Heap *h = newHeap(2);
deleteRoot(h);
addElement(h,12);
addElement(h,5);
addElement(h,7);
addElement(h,15);
printHeap(h);
return 0;
}
Thank you in advance!
In order to avoid your call-by-value problem in C, use a pointer to pointer as parameter for your root-deletion function.
void deleteRoot(Heap **h)
{
/* assuming that h is not NULL, which is guaranteed with "&something" */
if((*h)!=NULL && (*h)->left == NULL && (*h)->right == NULL) *h = NULL;
/* ... */
}
int main()
{
int i;
Heap *h = newHeap(2);
deleteRoot(&h);
/* ... */
return 0;
}

XOR maximization using a trie

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.

Resources