Parse Tree program Error - c

i have one error in that code for parsing expressions, it says
"146 C:\Dev-Cpp\z.c conflicting types for 'show_tree' 111
C:\Dev-Cpp\z.c previous implicit declaration of 'show_tree' was here"
help please...
#include<stdio.h>
#include<stdlib.h>
int getOperatorPosition(char);
#define node struct tree1
int matrix[5][5]=
{
{1,0,0,1,1},
{1,1,0,1,1},
{0,0,0,2,3},
{1,1,3,1,1},
{0,0,0,3,2}
};
int tos=-1;
void matrix_value(void);
//node create_node(char,*node);void show_tree( node *);
int isOperator(char);
struct tree1
{
char data;
node *lptr;
node *rptr;
}
*first;
struct opr
{
char op_name;
node *t;
}
oprate[50];
char cur_op[5]= {'+','*','(',')','['};
char stack_op[5]= {'+','*','(',')',']'};
int main()
{
char exp[10];
int ssm=0,row=0,col=0;
node *temp;
// clrscr();
printf("Enter Exp : ");
scanf("%s",exp);
matrix_value();
while(exp[ssm] != '\0')
{
if(ssm==0)
{
tos++;
oprate[tos].op_name = exp[tos];
}
else
{
if(isOperator(exp[ssm]) == -1)
{
oprate[tos].t = (node*) malloc(sizeof(node));
oprate[tos].t->data = exp[ssm];
oprate[tos].t->lptr = '\0';
oprate[tos].t->rptr = '\0';
}
else
{
row = getOperatorPosition(oprate[tos].op_name);
col = getOperatorPosition(exp[ssm]);
if(matrix[row][col] == 0)
{
tos++;
oprate[tos].op_name = exp[ssm];
}
else if(matrix[row][col] == 1)
{
temp = (node*) malloc(sizeof(node));
temp->data = oprate[tos].op_name;
temp->lptr = (oprate[tos-1].t);
temp->rptr = (oprate[tos].t);
tos--;
oprate[tos].t = temp;
ssm--;
}
else if(matrix[row][col] == 2)
{
//temp = (node*) malloc (sizeof(node));
temp = oprate[tos].t;
tos--;
oprate[tos].t = temp;
}
else if(matrix[row][col] == 3)
{
printf("\nExpression is Invalid...\n");
printf("%c %c can not occur simultaneously\n",oprate[tos].op_name,exp[ssm]);
break;
}
}
}
ssm++;
}
printf("show tree \n\n\n");
show_tree(oprate[tos].t);
printf("Over");
}
int isOperator(char c)
{
int i=0;
for(i=0; i<5; i++)
{
if(c==cur_op[i] || c==stack_op[i])
{
break;
}
}
if(i==5)
{
return (-1);
}
else
{
return i;
}
}
int getOperatorPosition(char c)
{
int i;
for(i=0; i<5; i++)
{
if(c==cur_op[i] || c==stack_op[i])
{
break;
}
}
return i;
}
void show_tree(node *start)
{
if(start->lptr != NULL)
{
show_tree(start->lptr);
}
if(start->rptr != NULL)
{
show_tree(start->rptr);
}
printf("%c \n",start->data);
}
void matrix_value(void)
{
int i,j;
printf("OPERATOR PRECEDENCE MATRIX\n");
printf("==========================\n");
for(i=0; i<5; i++)
{
printf("%c ",stack_op[i]);
}
printf("\n");
for(i=0; i<5; i++)
{
printf("%c ",cur_op[i]);
for(j=0; j<5; j++)
{
if(matrix[i][j] == 0)
{
printf("< ");
}
else if(matrix[i][j] == 1)
{
printf("> ");
}
else if(matrix[i][j] == 2)
{
printf("= ");
}
else if(matrix[i][j] == 3)
{
printf(" ");
}
}
printf("\n");
}
}

declare your show_tree function before main.
i.e. before struct tree1:
int isOperator(char );
void show_tree(node *start);
struct tree1
{
char data;
node *lptr;
node *rptr;
}
*first;
...

Related

Popping a float into a char to use as ascii code gives off a crash

while (!isEmpty(s))
{
*c = pop(s);
strcat(postfix, c);
strcat(postfix, " ");
}
This is where the crash happens specifically at the *c line. When i display the stack it has a value of 43.00000 which means it contains the '+' in ASCI code.
I also used these 3 lines above this specific one in two loops which gave no error.
float pop(stack *s)
{
float x = s->top->data;
node *temp = s->top;
s->top = s->top->next;
free(temp);
return x;
}
Here is the pop function.
Also this works in vscode and the crashes happen in codeblocks only
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
typedef struct node
{
float data;
struct node *next;
} node;
typedef struct
{
node *top;
} stack;
node *newNode(float x)
{
node *n = malloc(sizeof(node));
n->data = x;
n->next = NULL;
return n;
}
stack *init()
{
stack *s = malloc(sizeof(stack));
s->top = NULL;
return s;
}
float pop(stack *s)
{
float x = s->top->data;
node *temp = s->top;
s->top = s->top->next;
free(temp);
return x;
}
void push(stack *s, float x)
{
node *n = newNode(x);
if (s->top == NULL)
s->top = n;
else
{
n->next = s->top;
s->top = n;
}
}
float peek(stack *s)
{
float x = s->top->data;
return x;
}
int isEmpty(stack *s)
{
return (s->top == NULL);
}
void display(stack *s)
{
stack *temp = init();
while (!isEmpty(s))
push(temp, pop(s));
while (!isEmpty(temp))
{
printf("%f ", peek(temp));
push(s, pop(temp));
}
printf("\n");
}
int priority(char op)
{
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
if (op == '^')
return 3;
else
return 0;
}
int isOperator(char op[5])
{
if (!strcmp(op, "+") || !strcmp(op, "-") || !strcmp(op, "*") || !strcmp(op, "/") || !strcmp(op, "^") || !strcmp(op, "(") || !strcmp(op, ")"))
return 1;
else
return 0;
}
int isDigit(char digit[20])
{
int i = 0;
if (digit[0] == '-')
i++;
for (i; digit[i] != '\0'; i++)
if (!isdigit(digit[i]) && digit[i] != '.')
return 0;
return 1;
}
char *infixToPostfix(char *infix)
{
char postfix[100] = "", tokens[20][2000], *temptok, *c;
int i = 0;
temptok = strtok(infix, " ");
strcpy(tokens[i++], temptok);
while (temptok != NULL)
{
temptok = strtok(NULL, " ");
if (temptok != NULL)
strcpy(tokens[i++], temptok);
}
int ntok = i;
stack *s = init();
for (i = 0; i < ntok; i++)
{
if (isDigit(tokens[i]) && strcmp(tokens[i], "-"))
{
strcat(postfix, tokens[i]);
strcat(postfix, " ");
}
else if (isOperator(tokens[i]))
{
if (isEmpty(s))
push(s, tokens[i][0]);
else if (tokens[i][0] == '(')
push(s, tokens[i][0]);
else if (tokens[i][0] == ')')
{
while (peek(s) != '(')
{
*c = pop(s);
strcat(postfix, c);
strcat(postfix, " ");
}
pop(s);
}
else
{
while (!isEmpty(s) && priority(peek(s)) >= priority(tokens[i][0]) && tokens[i][0] != '(')
{
*c = pop(s);
strcat(postfix, c);
strcat(postfix, " ");
}
push(s, tokens[i][0]);
}
}
}
display(s);
system("pause");
while (!isEmpty(s))
{
*c = pop(s);
strcat(postfix, c);
strcat(postfix, " ");
}
strcpy(infix, postfix);
return infix;
}
int main()
{
char infixExpr[256] = "";
printf("Enter an expression you want to evaluate or Ctrl+Z to exit: ");
while (fgets(infixExpr, 255, stdin) != NULL)
{
replaceNewLineBySpace(infixExpr);
char *postfix = infixToPostfix(infixExpr);
printf("Postfix : %s\n", postfix);
float result = evaluatePostfix(postfix);
printf("Result: %f\n", result);
system("pause");
// exit(1);
}
return 0;
}

Convert type from char to string when it's passed by a function

I'm new to programming, while I know there are better codes out there for this question I sort of don't understand why this isn't working, the value returned by pop2() here is a part of a string which is why for %d it doesn't print the correct value but for %c it does
int n = pop2();
printf("n is now %c\n", n);
thus even numbers are of string type for s = "3[a2[c]]" I want my loop to run the number of times that is returned by pop (2 and then 3 in this case), since the value returned by pop2() is of char type even after using atoi it doesn't work
I tried doing
int n = atoi(pop2());
//or even
char* n = pop2();
int num = atoi(n);
but it still wouldn't work, here's the entire code of the function, I've typed out printf statements to help me recognize where I was going wrong, I'd be so grateful if you don't mind helping me out. Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <ctype.h>
struct node
{
int data;
struct node *link;
} *top = NULL;
struct node2
{
int data;
struct node2 *link;
} *top2 = NULL;
int isEmpty()
{
if (top == NULL)
{
return 1;
}
return 0;
}
int isEmpty2()
{
if (top2 == NULL)
{
return 1;
}
return 0;
}
int pop()
{
if (isEmpty())
{
return 0;
}
int val;
val = top->data;
top = top->link;
return val;
}
int pop2()
{
if (isEmpty2())
{
return 0;
}
int val;
val = top2->data;
top2 = top2->link;
return val;
}
void push(int data)
{
struct node *new = (struct node *)malloc(sizeof(struct node));
if (new == NULL)
{
exit(1);
}
new->data = data;
new->link = NULL;
new->link = top;
top = new;
}
void push2(int data)
{
struct node2 *new = (struct node2 *)malloc(sizeof(struct node2));
if (new == NULL)
{
exit(1);
}
new->data = data;
new->link = NULL;
new->link = top2;
top2 = new;
}
int peek()
{
if (isEmpty())
{
return 0;
}
return top->data;
}
int peek2()
{
if (isEmpty2())
{
return 0;
}
return top2->data;
}
char *decodeString(char *s, char *arr)
{
for (int i = 0; i < strlen(s); i++)
{
if (s[i] == '[')
{
printf("pushing s[i] that is %c on stack 1\n", s[i]);
push(s[i]);
}
if (isalpha(s[i]))
{
printf("pushing %c on stack 2\n", s[i]);
push2(s[i]);
}
if (isdigit(s[i]))
{
printf("pushing %c on stack 2\n", s[i]);
push2(s[i]);
}
if (s[i] == ']')
{
if (peek() == '[')
{
printf("s[i] is %c and peek element is %c \n", s[i],
peek());
printf("%c is now popped out next element in stack one is %c\n", pop(), peek());
if (isalpha(peek2()))
{
printf("element in stack 2 now is %c\n", peek2());
char ch = pop2();
printf("ch now is %c\n", ch);
strcat(arr, &ch);
printf("arr after strncating is:");
printf("%s ", arr);
printf("\n");
}
if (isdigit(peek2()))
{
printf("element in stack 2 now is %c\n", peek2());
int n = pop2();
printf("n is now %c\n", n);
printf("current arr is %s\n", arr);
while (n < 0)
{
strcat(arr, &arr);
printf("i. %d strncated %s\n", i, arr);
n--;
}
}
}
}
}
for (int i = 0; i < 10; i++)
{
printf("%c ", arr[i]);
}
printf("\n");
return arr;
}
int main()
{
char s[100] = "3[a2[c]]";
char arr[10] = {0};
decodeString(s, arr);
return 0;
}
here's the output I'm getting, sorry for making this so long

Need help creating maxHeap function

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct listNode {
int id;
struct listNode *next;
} ListNode;
typedef struct treeNode {
char *word;
char *key;
int freq;
ListNode *head;
struct treeNode *left;
struct treeNode *right;
} TreeNode;
TreeNode *insertItem(TreeNode *root, char *gword);
void printTreeInorder(TreeNode *v);
void searchforexist(TreeNode *root, char *key);
int searchItem(TreeNode *root, char *word);
void Heap(TreeNode *arr[],TreeNode *root, int i);
void maxheap(TreeNode *arr[],int k);
void freeNodes(TreeNode *root);
#define MAX 25
int main() {
char in[MAX];
char word[MAX];
TreeNode *root = NULL;
int comp;
int f=0;
int t=0;
FILE *fp = fopen("input.txt", "r");
memset(word, 0, MAX);
if (fp != NULL) {
while (fscanf(fp, "%24s \n", word) != EOF) {
root = insertItem(root, word);//insert items
t++;
if (strcmp(word, "eof") == 0) break;
}
fclose(fp);
}
// User inputs word
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
while(comp!=0)
{
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
if(comp==1)
break;
f=searchItem(root,in);
printf("%d",f);
f=0;
printf("\n");
}
TreeNode *arr[t];
Heap(arr,root,t);// HEAPPPPPPPPPPPPPPPPPPPPPPPPPPPP
printTreeInorder(root);
printf("\n");
freeNodes(root);
return 0;
}
TreeNode *insertItem(TreeNode *root, char *gword) {
TreeNode *v = root;
TreeNode *pv = NULL;
while (v != NULL) {
pv = v;
int comp = strcmp(gword, v->word);
if (comp < 0) {
v = v->left;
} else if (comp > 0) {
v = v->right;
} else {
char *word = v->word;
searchforexist(root,v->word);
return root;
}
}
TreeNode *tmp = (TreeNode *)malloc(sizeof(TreeNode));
tmp->word = strdup(gword);
tmp->left = tmp->right = NULL;
tmp->freq = 1;
if (root != NULL) {
if (strcmp(gword, pv->word) < 0) {
pv->left = tmp;
} else {
pv->right = tmp;
}
} else
root = tmp;
return root;
}
void searchforexist(TreeNode *root, char *word) {
if(root == NULL) {
return;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
root->freq++;
} else {
searchforexist(comp < 0 ? root->left : root->right , word);
}
}
int searchItem(TreeNode *root, char *word)
{
if(root == NULL) {
return 0;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
return root->freq;
} else {
searchItem(comp < 0 ? root->left : root->right , word);
}
}
void Heap(TreeNode *arr[],TreeNode *root, int i)
{
int k=0;
while(k<i)
{
if(root==NULL){
maxheap(arr,k);
}
arr[k]=root;
k++;
if (k=i){
maxheap(arr,k);
break;
}
Heap(arr,root->left,k);
Heap(arr,root->right,k);
}
}
void maxheap(TreeNode *arr[],int k)
{
int i;
int j;
for (i = 0; i < k; i++)
{
for (j = 0; j < k; j++)
{
if(arr[i]->freq>arr[j]->freq)
{
TreeNode *tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
for (i = 0; i < k; i++)
{
printf("%s %d",arr[i]->word,arr[i]->freq);
}
}
void printTreeInorder(TreeNode *v)
{
if (v==NULL) return;
printf("(");
printTreeInorder(v->left);
printf(")");
printf(" %.4s ", v->word);
printf("(");
printTreeInorder(v->right);
printf(")");
}
void freeNodes(TreeNode *root) {
if (root == NULL) {
return;
}
freeNodes(root->left);
freeNodes(root->right);
if(root->word != NULL) free(root->word);
if(root->key != NULL) free(root->key);
free(root);
return;
}
This program reads a file and puts all strings to a binary search tree. Repeating words are not added but the frequency counter increases (searchforexist). Then the user types a word and the program displays the frequency of the word typed.
The above works fine using any input file.
However im having trouble with the next steps of the assignment:
After that the hole tree is suppose to be copied in a maxheap based on the frequency of each word. The heap must be created using array with size equal to the elements of a tree. Every cell of said array must contain a pointer that points to a node in the binary search tree so we can still access the word inside and its frequency.
The user then inputs an int number and the programm prints all words that have frequency less that the number inputed by the user.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct listNode {
int id;
struct listNode *next;
} ListNode;
typedef struct treeNode {
char *word;
char *key;
int freq;
ListNode *head;
struct treeNode *left;
struct treeNode *right;
} TreeNode;
TreeNode *insertItem(TreeNode *root, char *gword);
void printTreeInorder(TreeNode *v);
void searchforexist(TreeNode *root, char *key);
int searchItem(TreeNode *root, char *word);
void freeNodes(TreeNode *root);
#define MAX 25
int main() {
char in[MAX];
char word[MAX];
TreeNode *root = NULL;
int comp;
int f=0;
FILE *fp = fopen("input.txt", "r");
memset(word, 0, MAX);
if (fp != NULL) {
while (fscanf(fp, "%24s \n", word) != EOF) {
root = insertItem(root, word);//insert items
if (strcmp(word, "eof") == 0) break;
}
fclose(fp);
}
// User inputs word
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
while(comp!=0)
{
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
if(comp==1)
break;
f=searchItem(root,in);
printf("%d",f);
f=0;
printf("\n");
}
//heapcreating here
printTreeInorder(root);
printf("\n");
freeNodes(root);
return 0;
}
TreeNode *insertItem(TreeNode *root, char *gword) {
TreeNode *v = root;
TreeNode *pv = NULL;
while (v != NULL) {
pv = v;
int comp = strcmp(gword, v->word);
if (comp < 0) {
v = v->left;
} else if (comp > 0) {
v = v->right;
} else {
char *word = v->word;
searchforexist(root,v->word);
return root;
}
}
TreeNode *tmp = (TreeNode *)malloc(sizeof(TreeNode));
tmp->word = strdup(gword);
tmp->left = tmp->right = NULL;
tmp->freq = 1;
if (root != NULL) {
if (strcmp(gword, pv->word) < 0) {
pv->left = tmp;
} else {
pv->right = tmp;
}
} else
root = tmp;
return root;
}
void searchforexist(TreeNode *root, char *word) {
if(root == NULL) {
return;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
root->freq++;
} else {
searchforexist(comp < 0 ? root->left : root->right , word);
}
}
int searchItem(TreeNode *root, char *word)
{
if(root == NULL) {
return 0;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
return root->freq;
} else {
searchItem(comp < 0 ? root->left : root->right , word);
}
}
void printTreeInorder(TreeNode *v)
{
if (v==NULL) return;
printf("(");
printTreeInorder(v->left);
printf(")");
printf(" %.4s ", v->word);
printf("(");
printTreeInorder(v->right);
printf(")");
}
void freeNodes(TreeNode *root) {
if (root == NULL) {
return;
}
freeNodes(root->left);
freeNodes(root->right);
if(root->word != NULL) free(root->word);
if(root->key != NULL) free(root->key);
free(root);
return;
}
I and many of us make simple mistakes. Use the automated tools you have to increase your coding efficiency.
Save time, enable all compiler warnings - or use a better compiler.
warning: control reaches end of non-void function [-Wreturn-type]
searchItem() needs to return a value.
int searchItem(TreeNode *root, char *word) {
if (root == NULL) {
return 0;
}
int comp = strcmp(word, root->word);
if (comp == 0) {
return root->freq;
} else {
// searchItem(comp < 0 ? root->left : root->right, word);
return searchItem(comp < 0 ? root->left : root->right, word);
}
}
Other problems may exist.

Array of singly linked list won't delete node

I have an array[4] where each index of the array has a singly linked list that holds the following information: name, size. The switch statement controls what index the information will go into according to the size of the party.
Problem: When trying to delete a node according to the size (user inputs) the node will not delete.
I know that all of the cases of deletion have the proper syntax but I cannot figure out why my node will not delete. Appreciate any help.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
char name[20];
int size;
struct node *next;
}node;
node* head[4]={NULL,NULL,NULL,NULL};
node* tail[4]={NULL,NULL,NULL,NULL};
//
// proto's
//
void add_party(int, char name[], int size);
void delete_party(char name[], int size);
void list_parties(void);
void change_p_size(char name[], int size);
//
// main function
//
int main()
{
int x;
while (1)
{
fflush(stdin);
printf("\n\nEnter 1 to add a party\nEnter 2 to remove a party\nEnter 3 for the list of the party\nEnter 4 to change party size.\nEnter 5 to quit.\n\n");
// user interface
scanf("%d",&x);
switch(x)
{
char name[20]; //local variables
int size;
case 1:
printf("\nParty Name: ");
scanf("%s", name);
printf("\nParty Size: ");
scanf("%d", &size);
if(size == 0)
{
printf("\nThat is not a valid command. Party not added!\n");
}
if(size >= 1 && size <= 2)
{
add_party(0, name, size);
}
else if(size >= 3 && size <= 4)
{
add_party(1, name, size);
}
else if(size >= 5 && size <= 6)
{
add_party(2, name, size);
}
else if(size >= 7)
{
add_party(3, name, size);
}
break;
case 2:
printf("\nSize of party to delete: ");
scanf("%i", &size);
delete_party(NULL, size);
break;
case 3:
list_parties();
break;
case 4:
change_partysize();
break;
case 5:
exit(0);
default:
continue;
}
}
}
//
//add function
//
void add_party(int h, char *name, int size)
{
//create a new node
int i=0;
int breaker = 0;
node *p;
node *new_item;
new_item = (node *)malloc(sizeof(node)); // allocate memory the size of the struct
strcpy(new_item->name,name);
new_item->size = size;
if(head[h] == NULL && tail[h] == NULL) // if an empty list, create a head and tail
{
head[h] = new_item;
tail[h] = head[h];
new_item->next = NULL;
return;
}
//traversal
for(i=0; i<4; i++)
{
p = head[i];
while(p != NULL)
{
//check that no repeating names. delete nodes that do have repeating names
if(strcmp(p->name,name) == 0)
{
printf("\nSorry, that name is already taken\n");
free(new_item);
return;
}
p = p->next; //go to the next node in the list
}
}
tail[h]->next = new_item;
new_item->next = NULL;
tail[h] = new_item;
}
//
//delete function
//
void delete_party(char *name, int size)
{
int i=0;
int breaker = 0;
node *p;
node *previous;
if(name != NULL)
{
for(i=0; i<4; i++)
{
p = previous = head[i]; //make sure previous trails behind head
while(p != NULL)
{
int c = (strcmp(p->name,name)==0);
if(c==0)
{
breaker = 1;
break;
}
else
previous = p;
p = p -> next;
}
if(breaker==1)
break;
}
}
else
{
int group = -1;
if(size == 1 || size == 2)
{
group = 0;
}
if(size == 3 || size == 4)
{
group = 1;
}
if(size == 5 || size == 6)
{
group = 2;
}
if(size >= 7)
{
group = 3;
}
for(i = group; i > -1; i--)
{
node *p = head[i];
node *previous = head[i];
while(p != NULL)
{
if(p <= size)
{
breaker = 1;
break;
}
else
{
previous = p;
p = p-> next;
}
}
if(breaker)
break;
}
}
if(p == NULL)
return;
if(head[i] == tail[i] && head[i] != NULL) // case 1, empty list
{
printf("\nList is empty!\n");
return;
}
else if(p == tail[i] && p == head[i]) // case 2, one element
{
head[i] = NULL;
tail[i] = NULL;
free(p);
}
else if(p == head[i]) // case 3, delete from the head
{
head[i] = head[i] -> next;
tail[i] = NULL;
free(p);
}
else if(p == tail[i]) // case 4, delete from tail
{
tail[i] = previous;
tail[i] -> next = NULL;
free(p);
}
else // case 5, delete from middle
{
previous -> next = p -> next;
free(p);
}
}
//
// list function
//
void list_parties(void)
{
int i = 0;
node *p=head;
for(i=0; i<4; i++)
{
p=head[i];
while(p != NULL)
{
printf("\n\n%s, %d\n\n", p->name, p->size);
p=p->next;
}
}
}
//
// change function
//
void change_partysize(char *name, int size)
{
int absolute_value = 0;
int comparison = 0;
int current_size = 0;
printf("\nWhat name is your party under?\n");
scanf("%s", name);
//check if the name
printf("\nWhat would you like to change the size to?\n");
scanf("%d", &size);
node *p;
while(p != NULL)
{
if(p->name == name) //new size falls into same range as the size coorelating to the name
{
current_size = p->size;
absolute_value = abs(size - current_size);
comparison = size - current_size;
if(current_size > 7 && size > 7)
{
current_size = size;
return;
}
else if(absolute_value >= 1)
{
//delete the node's value but not the name
delete_party(NULL, size);
//insert node with new name & dif size
add_party(NULL, name, size);
}
else
{
printf("\nYou did not enter a different party size\n");
return;
}
}
}
}
You're declaring new variables p and previous inside the for loop when you delete by size. So when the code after the loop uses these variables, it's using the uninitialized variables declared at the top of the function. Get rid of the declarations and just assign the variables.
Also, if (p <= size) appears to be a typo for if (p->size <= size). I'm surprised you didn't get a compiler warning for that.
You can also replace the if(breaker) check with a test in the for header.
for(i = group; !breaker && i > -1; i--)
{
p = head[i];
previous = head[i];
while(p != NULL)
{
if(p->size <= size)
{
breaker = 1;
break;
}
else
{
previous = p;
p = p-> next;
}
}
}

top-bottom binary tree display

The following code displays my created binary tree from left to right on the console window. How do I print it from the top to the bottom, as you would on paper?
// Binary Trees Implementation
#include<stdio.h>
#include<stdlib.h>
typedef struct BTNode
{
int key;
struct BTNode *left, *right;
};
void displayBT(BTNode *p, int level);
BTNode *buildBT();
void RSD(BTNode *p);
void SRD(BTNode *p);
void SDR(BTNode *p);
int main()
{
int op;
BTNode *root;
do
{
printf("\n 1. Build Binary Tree");
printf("\n 2. Display Binary Tree");
printf("\n 3. Display Traversals");
printf("\n 0. Exit");
printf("\n........................\n");
scanf("\n %d", &op);
switch(op)
{
case 1:
root=buildBT();
break;
case 2:
displayBT(root,0);
break;
case 3:
printf("\n Pre-Order:");
RSD(root);
printf("\n In-Order:");
SRD(root);
printf("\n Post-Order:");
SDR(root);
printf("\n.....................\n");
break;
}
} while(op);
}
BTNode *buildBT()
{
int value;
BTNode *p;
printf("\n k=");
scanf("%d",&value);
if(value!=0)
{
p=(BTNode *)malloc(sizeof(BTNode));
p->key = value;
p->left = buildBT();
p->right = buildBT();
} else p=NULL;
return p;
}
void displayBT(BTNode *p, int level)
{
if(p!=NULL)
{
displayBT(p->right, level+1);
for(int j=0; j<=level;j++)
printf(" ");
printf("%d \n", p->key);
displayBT(p->left, level+1);
}
}
void RSD(BTNode *p)
{
if(p!=NULL)
{
printf("%d ", p->key);
RSD(p->left);
RSD(p->right);
}
}
void SRD(BTNode *p)
{
if(p!=NULL)
{
SRD(p->left);
printf("%d ", p->key);
SRD(p->right);
}
}
void SDR(BTNode *p)
{
if(p!=NULL)
{
SDR(p->left);
SDR(p->right);
printf("%d ", p->key);
}
}
Ok so I uploaded the full code because I was having trouble with the suggestions and maybe I should have done this from the beginning.
gave it another go, actually tried it now. works for me
void print_box(FILE* out, int i)
{
static char buff[16] = {0};
sprintf(buff,"%d",i);
int n = strlen(buff);
static char buf2[16] = {0};
strcpy(buf2,"[ ]");
int nn = 2 - (n-1)/2 ;
for(i=0;i<n;++i)
buf2[nn+i] = buff[i];
fprintf(out,"%s",buf2);
}
void print_empty_box(FILE* out) { fprintf(out,"%s","[ - ]"); }
typedef struct NodeRowTag
{
struct NodeRowTag* nxt;
BTNode* node;
} NodeRow;
NodeRow* make_head()
{
NodeRow* nr;
nr = (NodeRow*) malloc(sizeof(NodeRow));
nr->node = 0;
nr->nxt = 0;
return nr;
}
void push_back( NodeRow* nr, BTNode* n )
{
while( nr->nxt )
{
nr = nr->nxt;
}
nr->nxt = (NodeRow*) malloc(sizeof(NodeRow));
nr->nxt->node = n;
nr->nxt->nxt = 0;
}
void del_all( NodeRow* nr )
{
if( nr->nxt )
del_all(nr->nxt);
free( nr );
}
NodeRow* print_and_next( FILE* out, NodeRow* nr, int rownum, int maxnum )
{
// init spacing
int spacing = 0;
int stride = 3;
for(int i=rownum; i<maxnum; ++i)
{
spacing += stride;
stride *= 2;
}
for(int i=0;i<spacing;++i)
fprintf(out, " " );
// inbetween spacing
spacing = 1;
stride = 6;
for(int i=rownum; i<maxnum; ++i)
{
spacing += stride;
stride *= 2;
}
//
NodeRow* nxt = make_head();
NodeRow* n = nr->nxt;
while(n)
{
BTNode* p = n->node;
if(p) {
print_box(out,p->key);
push_back(nxt,p->left);
push_back(nxt,p->right);
} else {
print_empty_box(out);
push_back(nxt,0);
push_back(nxt,0);
}
for(int i=0;i<spacing;++i)
fprintf(out, " " );
n=n->nxt;
}
fprintf(out, "\n" );
del_all(nr);
return nxt;
}
int max(int a,int b) { return (a>b)?a:b; }
int max_depth( BTNode* p )
{
if(!p) return 0;
return 1 + max( max_depth(p->left), max_depth(p->right) );
}
void PrittyPrint( FILE* out )
{
int n = max_depth(root);
NodeRow* nr = make_head();
push_back(nr,root);
for(int i=1; i<=n; ++i)
{
nr = print_and_next( out, nr, i, n );
}
del_all(nr);
}
By printing the value of the current node BEFORE recursing right/left!

Resources