pre_order traversal using stack in c - c

I am not able to figure out why the program is printing only first 3 characters of the tree.
Please help.
#include <stdio.h>
#include <malloc.h>
struct node
{
struct node *left;
char data;
struct node *right;
};
struct node *buildtree(int);
void pre_order(struct node*);
char a[]={'a','b','c','d','e','f','g','\0','\0','h','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
int main()
{
struct node *root;
root = buildtree(0);
printf("pre order traversal:\n");
pre_order(root);
}
struct node *buildtree(int n)
{
struct node *temp = NULL;
if(a[n]!='\0')
{
temp=(struct node*)malloc(sizeof(struct node));
temp->left=buildtree(2*n+1);
temp->data=a[n];
temp->right=(2*n+2);
}
return temp;
}
void pre_order(struct node* root)
{
char stack[30];
struct node* ptr;
int top=1;
stack[1]=NULL;
ptr=root;
while(ptr!=NULL)
{
printf("%c",ptr->data);
if(ptr->right!=NULL)
{
top=top+1;
stack[top]=ptr->right;
}
if(ptr->left!=NULL)
ptr=ptr->left;
else
{
ptr=stack[top];
top=top-1;
}
}
}

I'm surprised that compiled
char stack[30];
should be replaced by
struct node* stack[30];
There might be other problems.
You wrote a nice recursive routine to build the tree, why not write a recursive routine to do a pre-order traversal. It would be much easier to understand.

Simply calling something "stack" won't make it behave as one. When you push something onto a stack, the existing values get pushed down, and the reverse is true for popping.
I'd start with a working stack implementation, preferably with own functions for pushing and popping stuff.

Related

creating a list of nodes with C

I want to createe a list of nodes that links to each other, I use head to remember the address of the first node, prev to link, and newdata to get the input, but it turns out that my head prev and newdata are all in the same address, can someone help me with this plz
typedef struct node
{
void* stdPtr;
struct node* link;
}NODE;
NODE* createNode(void* std)
{
NODE* nodePtr;
nodePtr=(NODE*)malloc(sizeof(NODE));
nodePtr->stdPtr=std;
nodePtr->link=NULL;
return nodePtr;
}
typedef NODE* nodePtr;
int main(void)
{
FILE* fin;
fin=fopen("input.txt","r");
//define
int i=0;
intPtr ID,grade;
STD* stdinfo;
nodePtr head=NULL;
nodePtr prev=(nodePtr)malloc(sizeof(NODE));
//nodePtr newdata=(nodePtr)malloc(sizeof(NODE));
prev=head;
//malloc space to ptr
ID=(intPtr)malloc(sizeof(int));
grade=(intPtr)malloc(sizeof(int));
stdinfo=(STD*)malloc(sizeof(STD));
//read student data and compare
while(fscanf(fin,"%d%d",&(stdinfo->ID),&(stdinfo->grade))!=EOF)
{
nodePtr newdata=(nodePtr)malloc(sizeof(NODE));
newdata=createNode(stdinfo);
if (prev==NULL)
{
prev=newdata;
head=prev;//為什麼只有在這裡=prev後面會跑掉?
}
printf("%d %d\n",*(int*)head,*(int*)prev);
if(prev->link!=NULL)
{
prev=prev->link;
}
prev->link=newdata;
}
fclose(fin);
return 0;
}
Important parts are missing (types, input.txt) to run your program which makes it harder to help you.
You create an instance of STD prior to the loop, then overwrite whatever data you store in it on each iteration and store the address of that one instance in each node. You need to create an instance of both NODE and STD per loop iteration (or change the definition of NODE so it can hold the STD data instead of a pointer to STD).
You use this pattern a couple of times which allocate data, then immediately leak the data by overwriting the pointer:
nodePtr prev=(nodePtr)malloc(sizeof(NODE));
prev=head;
...
nodePtr newdata=(nodePtr)malloc(sizeof(NODE));
newdata=createNode(stdinfo);
Here is more straight forward version to get you going:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
void *stdPtr;
struct node* link;
} NODE;
NODE* createNode(void *std, NODE *prev) {
NODE *nodePtr = malloc(sizeof(NODE));
nodePtr->stdPtr=std;
nodePtr->link=prev;
return nodePtr;
}
void printNodes(NODE *tail) {
for(; tail; tail = tail->link) {
printf("%s\n", (const char *) tail->stdPtr);
}
}
int main(void) {
NODE *tail = NULL;
tail = createNode("hello", tail);
tail = createNode("world", tail);
printNodes(tail);
}

Structure, pointer and binary search tree in c

The below code is able to add only one element to tree.
Please check what is wrong with this code.
I tried creating a binary search tree with 8 nodes with values taken from array, and when I print the tree only the first element is printed i.e the first element of array.
May be I am not good with working of structure and pointer. Can you say more about pointers and structure in c.
I thank for your help.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *root=NULL;
void add(struct node**,struct node*);
void createtree(struct node **root){
int arr[8]={20,45,17,56,40,32,25,48};
int size=sizeof(arr)/sizeof(int);
struct node *temp=NULL;
for(int i=0;i<size;i++)
{
temp=(struct node *)malloc(sizeof(
struct node));
temp->data=arr[i];
temp->left=NULL;
temp->right=NULL;
add(root,temp);
}
}
void add(struct node **root,struct node *temp){
if(*root==NULL){
*root=temp;
return;
}
struct node *curr=*root;
if(temp->data< curr->data){
struct node *temper=curr->left;
add(&temper,temp);
}
else
{
struct node *temper=curr->right;
add(&temper,temp);
}
}
void print(struct node *root){
if(root!=NULL){
print(root->left);
printf("%d ",root->data);
print(root->right);
}
}
int main(){
createtree(&root);
print(root);
return 0;
}

Problems with creating a tree in C

I am trying to create a tree in C (I know how to make one in java, but since I am learning C I thought this would be a great way to really learn pointers), but I am not getting an output when I printf the root's data.
This is my code:
#include<stdio.h>
typedef struct Node
{
struct Node *right;
struct Node *left;
int data;
} Node;
Node* create_node(int data);
Node* create_root(int nodedata)
{
Node* root;
root->data = nodedata;
return root;
}
int main()
{
Node* root = create_root(5);
printf("%d", root->data);
return 0;
}
Is the problem how I am linking the nodes with left and right pointers, or how I am returning the function to a Node pointer?
You should allocate memory before use.
Node* create_root(int nodedata)
{
Node* root = calloc(1, sizeof(Node));
root->data = nodedata;
return root;
}

comiling error says "node undeclared" first use in program,although i made "node" a global one

#include<stdio.h>
#include<stdlib.h>
void print();
void insert(int);
struct node
{
int data;
struct node* next;
};
struct node* head;
void insert(int x)
{
struct node* temp=(node*)malloc(sizeof(node));
temp->data=x;
temp->next=head;
head=temp;
}
void print(void)
{
struct node* temp=head;
printf("the linked list is:\n");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
main()
{
head=NULL;
printf("how many numbers?\n");
int n,x,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the number:\n");
scanf("%d",&x);
insert(x);
print();
}
return 0;
}
comiling error says "node undeclared" first use in program,although i made "node" a global one
this code is just for creating a linked list and adding user input values into the front of the linked list
insert(int x) function does the insertion work.
The error message is clear enough. In the function insert you should prepand the name node with the keyword struct.
void insert(int x)
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
^^^^^^ ^^^^^^
Another way to escape the error is to use a typedef. For example
typedef struct node
{
int data;
struct node* next;
} node;
I presume when you say "first use" you mean the first line of insert where you try to allocate a node. But it is not the first; outside of the definition, that is 3 lines above, where you declare head to be a struct node*. (also note that inside the definition you use struct node* as well.)
The problem is that you did not define node; you defined struct node, and that is what you need to use.
You might be confused by C++, in which a struct tag becomes a typedef. Try this:
typedef struct node {
int data;
struct node* next;
} node;
Now you can just use node instead of struct node everywhere. Easier to read and easier to type.

How to create head node

I think I got it wrong in newList. Typedef struct implementations must not be change. This is a lab assignment in my school.. Thanks in advance :)
#include<stdio.h>
typedef struct node *nodeptr;
struct node {
int item;
nodeptr next;
};
typedef nodeptr List;
List newList();
newList creates a header and returns a pointer to the header node
void display(List list);
void addFront(List list, int item);
List newList(){
List list;
list=(nodeptr)malloc(sizeof(List));
list->next=NULL;
return list;
} //I think my new list is incorrect..
void display(List list){
nodeptr ptr=list;
while(ptr!=NULL){
printf("%d",ptr->item);
ptr=ptr->next;
}
printf("\n");
}
void addEnd(List list, int item){
nodeptr temp, ptr;
temp=(List)malloc(sizeof(nodeptr));
temp->item=item;
temp->next=NULL;
if(list->next==NULL)
list=temp;
else{
ptr=list;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=temp;
}
}
I can't seem to add 10 from the list..
int main(void){
List list=newList();
addEnd(list,10);
display(list);
}
There are many ways you can go about this depending on what you actually want (because just creating a node doesn't make a lot of sense by itself). But generally you have three common options — create it on the stack, create that node in the global memory, or allocate it dynamically. Below are some examples.
On stack
#include <stdlib.h>
struct node {
int item;
struct node *next;
};
int main()
{
struct node head;
head.item = 0;
head.next = NULL;
/* Do something with the list now. */
return EXIT_SUCCESS;
}
In Global Memory
#include <stdlib.h>
struct node {
int item;
struct node *next;
};
static struct node head;
int main()
{
/* Do something with the list now. */
return EXIT_SUCCESS;
}
Dynamic Allocation
#include <stdlib.h>
#include <stdio.h>
struct node {
int item;
struct node *next;
};
int main()
{
struct node *head;
head = calloc(1, sizeof(struct node));
if (head == NULL) {
perror("calloc");
return EXIT_FAILURE;
}
/* Do something with the list now. */
return EXIT_SUCCESS;
}
You can read up on any of the above example in any introductory C book.
Hope it helps. Good Luck!

Resources