Traversing a tree using C. It will accept a character and prints the post fix/ in fix/ pre fix.
The problem is when it prints the output it looks like this
input
a
b
c
d
e
f
g
h
i
IN ORDER: C abcdefghi
PRE ORDER: C abcdefghi
POST ORDER: ihgfedcba C
There are spaces and the character 'C' when I traverse and the pre and post order is wrong. I dont know what is wrong. I am wrong in getting the input here? using scanf to get the address of the char?
Here is the whole code
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
char data;
struct BST *lchild, *rchild;
}node;
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}
void insert(node *root, node *new_node)
{
if((new_node->data) < (root->data))
{
if((root->lchild)==NULL)
{
root->lchild=new_node;
}
else
{
insert(root->lchild,new_node);
}
}
if(new_node->data > root->data)
{
if((root->rchild)==NULL)
{
root->rchild=new_node;
}
else
{
insert(root->rchild,new_node);
}
}
}
void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->lchild);
putchar(temp->data);
inorder(temp->rchild);
}
}
void preorder(node *temp)
{
if(temp!=NULL)
{
putchar(temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
void postorder(node *temp)
{
if(temp!=NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
putchar(temp->data);
}
}
void main()
{
int i;
node *new_node, *root, *tmp, *parent;
node *get_node();
char c;
clrscr();
for(i=0;i<9;i++)
{
fflush(stdin);
new_node=get_node();
printf("\nenter element: ");
scanf("%c", &new_node->data);
if(root==NULL)
{
root = new_node;
}
else
{
insert(root, new_node);
}
}
printf("\n\nIN ORDER: ");
inorder(root);
printf("\nPRE ORDER: ");
preorder(root);
printf("\nPOST ORDER: ");
postorder(root);
getch();
}
There are spaces and the character 'C' when I traverse
This is most probably due to the missing initialization of root, as Joachim Pileborg noticed.
the pre and post order is wrong
They are not; apart from the spaces and the 'C', you have the degenerate (or pathological) tree
a
\
b
\
c
\
d
\
e
\
f
\
g
\
h
\
i
for which the output orders are correct.
Related
I have to create a program for a binary search tree for strings, which calculates how many times each word repeats, and it seems like I can't get the program to do as intended, because when printing it out, what should be printed first, are the words/characters smaller than the origin node, followed by the words/characters bigger than the origin node. But what my program does, it just prints it out in the order that I introduced the words/characters, I am still thinking about, how to realise the part of the program that will calculate the number of appearances of each word.
#include<stdio.h>
#include<stdlib.h>
#define MAX 15
typedef struct BST
{
char data[MAX];
struct BST *left;
struct BST *right;
} node;
node *create();
void insert(node *,node *);
void preorder(node *);
int main()
{
char ch;
node *root=NULL,*temp;
do
{
temp=create();
if(root==NULL)
{
root=temp;
}
else
{
insert(root,temp);
}
printf("\nDo you want to enter more(y/n)?");
ch=getch();
}
while(ch=='y'||ch=='Y');
printf("\nPreorder Traversal: ");
preorder(root);
return 0;
}
node *create()
{
node *temp;
printf("\nEnter data:");
temp=(node*)malloc(sizeof(node));
fgets(&temp->data,MAX,stdin);
temp->left=temp->right=NULL;
return temp;
}
void insert(node *root,node *temp)
{
if(temp->data<root->data)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;
}
}
void preorder(node *root)
{
if(root!=NULL)
{
printf("%s ",root->data);
preorder(root->left);
preorder(root->right);
}
}
Here's what I came up with, with the help of somebody in the comments, and it works as intended
void insert(node *root,node *temp)
{
int cmp_rezult=strcmp(temp->data,root->data);
printf("\nCompare:%d ", cmp_rezult);
if(cmp_rezult<0)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(cmp_rezult>0)
{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;
}
}
In insert you do:
temp->data<root->data
but that's not how you compare strings in C.
To compare strings use strcmp
Further it seems that insert miss a code block for handling "equal".
So something like:
int cmp_result = strcmp(temp, data<root->data);
if (cmp_result < 0)
{
// Handle less than
}
else if (cmp_result > 0)
{
// Handle greater than
}
else // i.e. cmp_result == 0
{
// Handle equal
}
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node{
char data;
int p;
struct node *ptr;
};
struct node *start=NULL;
struct node *insert()
{
struct node *new_node,*z;
int num;
char s;
printf("\nEnter -1 to stop.");
printf("\nEnter the characters and their priorities: ");
scanf("\n%c %d",&s,&num);
while(num!=-1)
{
new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=s;
new_node->p=num;
if(start==NULL)
{
start=new_node;
z=start;
new_node->ptr=NULL;
}
else
{
z->ptr=new_node;
new_node->ptr=NULL;
z=z->ptr;
}
scanf("%c %d",&s,&num);
}
return start;
}
struct node *display()
{
struct node *z;
z=start;
printf("\nDisplaying elements:\n");
while(z!=NULL)
{
printf("\t%c [Priority=%d]\n",z->data,z->p);
z=z->ptr;
}
return start;
}
struct node *sortit()
{
struct node *z,*q;
int t;
char x;
z=start;
while(z->ptr!=NULL)
{
q=z->ptr;
while(q!=NULL)
{
if(z->p>q->p)
{
t=z->p;
x=z->data;
z->p=q->p;
z->data=q->data;
q->p=t;
q->data=x;
}
q=q->ptr;
}
z=z->ptr;
}
return start;
}
struct node *new_insert()
{
struct node *y,*z;
int n;
char s;
y=(struct node *)malloc(sizeof(struct node));
printf("\nEnter character and priority for new node:");
scanf("%c %d",&s,&n);
printf("%c",s);
y->data=s;
y->p=n;
printf("%c",y->data);
printf("%d",y->p);
if(n<start->p)
{
y->ptr=start;
start=y;
printf("%d",y->p);
}
else
{printf("\nff");
z=start;
while(z->ptr->p<=n&&z->ptr!=NULL)
z=z->ptr;
y->ptr=z->ptr;
z->ptr=y;
}
return start;
}
int main()
{
insert();
display();
sortit();
display();
new_insert();
display();
return 0;
}
In this C code, I have tried to implement priority queues.
Everything works perfectly fine except the new_insert() function. The print statements after y->p=n; in new_insert() function print 0.
Hence, the function doesn't work properly. Also, in display() function the print statement prints the [Priority] twice.
Hence, I am not able to add an external node in my priority queue.
Well, you code is not far from working I think.
There are some problems that can be corrected:
the scanf usage is problematic
%c selector must be use with caution, use " %c %d" to prevent end of line problems
return value must be checked
in function insert, z may not be initialized (if insert() is called when start is not NULL)
You don't need to cast malloc returned value.
I tested the following code with this input:
a 2
b 3
c 1
d -1
e 0
And I got this result:
Enter -1 to stop.
Enter the characters and their priorities:
Displaying elements:
a [Priority=2]
b [Priority=3]
c [Priority=1]
Displaying elements:
c [Priority=1]
a [Priority=2]
b [Priority=3]
Enter character and priority for new node:
s: 'e' n: '0'
e00
Displaying elements:
e [Priority=0]
c [Priority=1]
a [Priority=2]
b [Priority=3]
Seems to work isn't? You can test it online
And here's the corrected code:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node{
char data;
int p;
struct node *ptr;
};
struct node *start=NULL;
struct node *insert()
{
/* initialize z in case of start is not null */
struct node *new_node,*z = start;
int num, ok;
char s;
printf("\nEnter -1 to stop.");
printf("\nEnter the characters and their priorities: ");
/* read the scanf return value */
ok = scanf(" %c %d",&s,&num);
/* and assert two elements have been read*/
while(ok == 2 && num!=-1)
{
new_node=malloc(sizeof(struct node));
new_node->data=s;
new_node->p=num;
if(start==NULL)
{
start=new_node;
z=start;
new_node->ptr=NULL;
}
else
{
z->ptr=new_node;
new_node->ptr=NULL;
z=z->ptr;
}
ok = scanf(" %c %d",&s,&num);
}
return start;
}
struct node *display()
{
struct node *z;
z=start;
printf("\nDisplaying elements:\n");
while(z!=NULL)
{
printf("\t%c [Priority=%d]\n",z->data,z->p);
z=z->ptr;
}
return start;
}
struct node *sortit()
{
struct node *z,*q;
int t;
char x;
z=start;
while(z->ptr!=NULL)
{
q=z->ptr;
while(q!=NULL)
{
if(z->p>q->p)
{
t=z->p;
x=z->data;
z->p=q->p;
z->data=q->data;
q->p=t;
q->data=x;
}
q=q->ptr;
}
z=z->ptr;
}
return start;
}
struct node *new_insert()
{
struct node *y,*z;
int n, ok;
char s;
printf("\nEnter character and priority for new node:");
ok = scanf(" %c %d",&s,&n);
if (2 == ok)
{
/* alloc y after having check that user gave usage stuff */
y = malloc(sizeof(struct node));
y->data=s;
y->p=n;
printf("%c",y->data);
printf("%d",y->p);
if(n<start->p)
{
y->ptr=start;
start=y;
printf("%d",y->p);
}
else
{
printf("\nff");
z=start;
while(z->ptr->p<=n&&z->ptr!=NULL)
z=z->ptr;
y->ptr=z->ptr;
z->ptr=y;
}
}
return start;
}
int main()
{
insert();
display();
sortit();
display();
new_insert();
display();
return 0;
}
I'm new to C language and it's been harder for me to work with pointers after working in Java😥
I was trying to write a code of finding a path (not necessary minimum) between two nodes in a graph using breadth-first-search.
Here is my code :
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 200
void push(int a);
int pop(void);
void bfs(int a,int b,int len);
int nextnode(int a);
typedef struct node{
int data;
struct node* next;
}node;
int res[MAXSIZE];
int visited[MAXSIZE];
int rear,front;
node* graph[MAXSIZE];
int len;
int path[MAXSIZE];
int nextnode(int a)
{
if(graph[a]==NULL)
return -1;
else
{
struct node* c=graph[a];
while(visited[c->data]!=1 && c!=NULL)
{
c=c->next;
}
if(c==NULL)
return -1;
else
return c->data;
}
}
void push(int a)
{
path[rear]=a;
rear++;
}
int pop()
{
if(front==rear)
return -1;
int num=path[front];
front++;
return num;
}
int main()
{
rear=0;
len=0;
front=0;
int n,e;
int i,a,b;
printf("%s\n%s", "Inputting Graph... ","Enter number of nodes and edges: ");
scanf("%d %d",&n,&e);
printf("%s %d %s\n", "Graph Created with",n,"nodes without any edge.");
printf("%s\n","Enter the edges in 1 2 format if an edge exist from Node 1 to Node 2" );
for(i=1;i<=n;i++)
{
graph[i]=NULL;
visited[i]=0;
}
struct node* new = (struct node*)malloc(sizeof(struct node));
for(i=0;i<e;i++)
{
scanf("%d %d",&a,&b);
new->data=b;
new->next=NULL;
struct node* curr=graph[a];
if(curr==NULL)
{
graph[a]=new;
}
else
{
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=new;
}
}
printf("%s\n", "Graph Created Successfully.");
printf("%s", "Enter the node numbers between which the path is to be found between: ");
scanf("%d %d",&a,&b);
bfs(a,b,0);
printf("Length is %d\n",len);
for(i=1;i<=len;i++)
{
printf("%d\n",res[len]);
}
}
void bfs(int a,int b,int len)
{
int c;
visited[a]=1;
int flag=0;
while(a!=-1)
{
c=nextnode(a);
while(c!=-1)
{
c=nextnode(a);
if(c==b)
{
flag=1;
break;
}
push(c);
visited[c]=1;
}
len++;
res[len]=a;
if(flag==1)
{
res[len]=b;
break;
}
a=pop();
}
}
I know it's huge, but please mind going through it once. The problem I'm getting is Segmentation Fault after I input all the values, and before dfs() function call! Please Help.
For understanding: I have used array of Lists. Each array index denotes a node and the list denotes all the edges it is connected to. eg: if my Graph has 1->2, 1->3, 2-3 edges;
graph[1] will have a list 2->3->NULL. And graph[2] will have 3->NULL.
Thank you.
EDIT
As pointed out by Aditi, the error was in the line where nextnode function ran the while loop. After changing the code to
while(c != NULL && visited[c->data] == 1 )
the program ran flawlessly.
Thanks!
I think what you are trying to do is not graph[i] = NULL but graph[i]->next = NULL
I need to sort the numbers that are entered in a list, but I am doing something wrong and it's sorting all of them except the first one.Any ideas how to fix this?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* List;
void Add (struct node* p, int d)
{
struct node* q;
q=malloc(sizeof(struct node));
if (q==NULL)
printf("Not enaugh memory!");
else
{
q->data=d;
if(List==NULL)
{
q->next=NULL;
List=q;
}
else
{
struct node *ptr=List;
while((ptr->next!=NULL)&&(ptr->next->data>d))
{
ptr=ptr->next;
}
q->next=ptr->next;
ptr->next=q;
}
}
}
int main()
{
int n,i,a;
printf("How much numbers are you going to enter? ");
scanf("%d",&n);
for (i=1; i<=n; i++)
{
printf("\nEnter a number: ");
scanf("%d",&a);
Add(List,a);
}
printf("\nThe sorted numbers are: ");
struct node *ptr=List;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n\n");
system("PAUSE");
return 0;
}
Thanks for the help in advance :-)
in add() function,
if(List==p)
this statement is true for all elements you insert to list since the call to add is,
Add(List,a);
so p=List. therefore the sorting code written in else part is not executed.
Also add statements to check for empty initial list.
You can use code similar to this,
void Add (int d)
{
struct node* q;
q=malloc(sizeof(struct node));
if (q==NULL)
printf("Not enaugh memory!");
else
{
q->data=d;
if(List==NULL)
{
q->next=NULL;
List=q;
}
else
{
struct node *ptr=List;
while((ptr->next!=NULL)&&(ptr->next->data>d))
{
ptr=ptr->next;
}
q->next=ptr->next;
ptr->next=q;
}
}
}
Since list is a global variable you dont need to pass it to Add() function. change the function call to
Add(a);
void Add (struct node* p, int d){
struct node* q;
q=malloc(sizeof(struct node));
if (q==NULL)
printf("Not enaugh memory!");
else{
q->data=d;
if(List==NULL || List->data < d){//modify this line
q->next= List;//and change NULL to List
List=q;
} else {
struct node *ptr=List;
while((ptr->next!=NULL)&&(ptr->next->data>d)){
ptr=ptr->next;
}
q->next=ptr->next;
ptr->next=q;
}
}
}
You always call Add with List as the first parameter, so it's alway true inside Add that (List==p). Consequently each new item is just inserted at the front of the list and there is no sorting at all.
EDIT 1
A good practice would be sending a list to the Add routine as a parameter. Or, if you want to keep it external, just don't give it to Add at all and test if(List == NULL)
void Add( int d)
{
// ... alloc 'q' and fill q->d here, then:
if(List == NULL)
{
q->next = NULL;
List = q;
}
else
{
struct node *b; // put q after b
for( b = List; b->next != NULL; b = b->next)
if( b->next->data >= d)
break;
q->next = b->next;
b->next = q;
}
}
EDIT 2
Example of transferring the list to a function by parameter
void Add( struct node **n, int d)
{
// ... alloc 'q' and fill q->d here, then:
while( *n != NULL && (*n)->data < d)
n = & (*n)->next;
q->next = *n;
*n = q;
}
int main()
{
// ...
Add( &List, a);
// ...
}
I am getting error while executing this. Compiler does not give any error but when executed it give random output.
What am i doing is taking input from user & storing them to linked list & then implementing insertion sort.
( I am able to call the subroutine insertion sort, so I guess the problem lies within subroutine only)
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODEPTR;
NODEPTR getnode();
NODEPTR insertionSortLinkedList(NODEPTR head);
int main()
{
int i,n,temp;
NODEPTR head,lptr,prevlptr;
printf("No of input integers to be sorted\n");
scanf("%d",&n);
if (n<2){printf("n should be atleast 2 \n");return 0;}
printf("\nType space-separated array of %d integers\n",n);
scanf("%d",&temp);
head=getnode();
head->info=temp;
head->next=NULL;
prevlptr=head;
for (i=0;i<n-1;i++)
{
scanf("%d",&temp);
lptr=getnode();
lptr->info=temp;
prevlptr->next=lptr;
lptr->next=NULL;
prevlptr=lptr;
}
head=insertionSortLinkedList(head);
lptr=head;
while(lptr!=NULL)
{
printf("%d ",lptr->info);
prevlptr=lptr;
lptr=lptr->next;
free(prevlptr);
}
return 0;
}
NODEPTR getnode()
{
NODEPTR p;
p=(struct node*)malloc(sizeof(struct node));
return p;
}
NODEPTR insertionSort(NODEPTR head)
{
NODEPTR listptr,tempptr,prevptr,prevtempptr;
prevptr=head;
listptr=prevptr->next;
while(listptr!=NULL)
{
while (listptr->info < prevptr->info)
{
prevptr->next=listptr->next;
tempptr=head;
prevtempptr=head;
while(tempptr->info <= listptr->info)
{
prevtempptr=tempptr;
tempptr=tempptr->next;
}
if(tempptr->info == prevtempptr->info)
{
listptr->next=head;
head=listptr;
}
else
{e
listptr->next=prevtempptr->next;
prevtempptr->next=listptr;
}
listptr=prevptr->next;
if (listptr==NULL)
break;
}
prevptr=prevptr->next;
if (prevptr=NULL)
break;
listptr=prevptr->next;
}
return(head);
}
What is wrong with my code and how do I fix it?
The 6th line form last
if (prevptr=NULL)
it should be
if (prevptr==NULL)
Single "=" does the assignment instead of comparison.