typedef struct word {
char *str;
int freq;
struct word *right;
struct word *left;
} Word;
Word *root = NULL; //global
while(pCounter != NULL){
if(root == NULL){
Word *x = (Word *)malloc(sizeof(Word));
x->str = (char*)malloc(strlen(pCounter->str)+1);
//printf("%s", node->str);
strcpy(x->str,pCounter->str);
x->freq = pCounter->freq;
x->left = NULL;
x->right = NULL;
root = x;
}
else {
Insert(pCounter, root);
}
pCounter = pCounter ->pNext;
}
void * Insert(Word *node, Word *root)
{
printf("inserted%s\n", node->str);
if(root==NULL)
{
Word *x = (Word *)malloc(sizeof(Word));
x->str = (char*)malloc(strlen(node->str)+1);
//printf("%s", node->str);
strcpy(x->str,node->str);
x->freq = node->freq;
x->left = NULL;
x->right = NULL;
return x;
//node = root;
}
else if (strcmp(node->str, root->str)==0){
root -> freq = root->freq+1;
}
else if (strcmp(node->str, root->str)<1){
root->left = Insert(node,root->left);
}
else {
root->right = Insert(node, root->right);
}
return node;
}
void ordered(Word *n){
//printf("ordered");
if(n != NULL){
ordered(n->left);
printf("%-30s %5d\n", n->str, n->freq);
ordered(n->right);
}
}
I'm trying to build a binary search tree to process a linked list into an ordered bst. I can get the output of root to show up correctly but not anything else. It spits out some garbage and i'm not sure why. I set up a printf statement and it shows that it is inserting actual strings. Am i doing something wrong? This isn't all the code but I think it's enough so people can understand what i'm doing. Suggestions?
return node; --> return root; As per BLUEPIXY's comment, this was the correct answer.– BLUEPIXY 2 mins ago
Related
For homework I was given this code with the directive to implement a recursive function that calls itself on the next node in the list in main unless the current node is NULL or the value of the current node is equal to 'target'
My recent attempt is the fenced part of the code below. I can get it to print 0, but that's not the whole list. I'm not sure what I'm doing wrong as I've not had much experience with linked lists and nodes.
typedef struct node {
struct node* next;
unsigned short index;
char* value;
} node;
node* create_node(unsigned short index, char* value) {
node* n = malloc(sizeof(node));
n->value = value;
n->index = index;
n->next = NULL;
return n;
}
node* create_nodes(char* values[], unsigned short index, unsigned short num_values) {
if(num_values == 0) {
return NULL;
}
node* n = create_node(index, values[0]);
n->next = create_nodes(values + 1, index + 1, num_values - 1);
return n;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node* find_match(node* cur, char* target) {
if(cur == NULL){
return NULL;
}
if(cur->value != NULL){
node* result = create_node(cur->index, cur->value);
result->next = find_match(cur->next, cur->value);
}else{
return find_match(cur->next, cur->value);
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main() {
char* values[] = {
"foo", // 0
"bar", // 1
"baz", // 2
"duh", // 3
"dunk", // 4
"derp" // 5
};
node* head = create_nodes(values, 0, 6);
node* target = find_match(head, "dunk");
printf("%d\n", target->index);
return 0;
}
No error messages were given, except a prior segmentation fault I've already 'fixed' but I think it's supposed to print the whole list.
You can insert a single element at a time and send the each element using loop because you know the size of array.Then you have to little change in your code.
struct linkList {
int data;
linkList* next;
}node;
node create(int val){
node tmp;
tmp = (node)malloc(sizeof(struct linkList));
tmp->data = val;
return tmp;
}
node* insertNodeAtHead(linkList* llist,int data) {
node tmp;
tmp = create(data);
tmp->next = llist;
return tmp;
}
Then you can search with your Key just like printing the all element in the List
void print(linkList* head) {
while(head !=NULL){
printf("%d\n",head->data); // check here is this your key or Not
head = head->next;
}
}
But this question is known and before posting any question make sure you try and Search enough in Google !!. Hope you get the idea and implement it in your own way.
There are a few issues in the code.
The problem is in the findmatch function. In this as per the problem statement, the target node should be returned if it is present, else NULL should be returned. This can be achieved as below.
node* find_match(node* cur, char* target) {
if(cur == NULL){
return NULL;
}
if(strcmp(cur->value,target) ==0){
return (cur);
}else if (cur->value != NULL){
return find_match(cur->next, target);
}
else {
return NULL;
}
}
Additional points
In the create_node function you are directly copying the string pointer. This may work in this specific case, but you should ideally allocate memory for the value field separately.
node* create_node(unsigned short index, char* value) {
node* n = malloc(sizeof(node));
n->value = strdup(value);
n->index = index;
n->next = NULL;
return n;
}
While printing the value, you should check if the returned value from findmatch is NULL
node* target = find_match(head, "dunk");
if (target != NULL) {
printf("%d\n", target->index);
}
else {
printf (" Not found\n");
}
I have to create a function that receives in input the name of a file, which contains words in a casual order, and it has to return a pointer to a list where every node contains a pointer to each word. How can I do?
typedef struct _NODE {
char* word;
struct _NODE *next;
} NODE;
I tried to implement this
NODE* createFromFile(char* nameFile)
{
FILE* ptr = fopen(nameFile, "r");
if (ptr == NULL)
{
return NULL;
}
NODE* n = NULL;
NODE* temp= n;
while (!feof(ptr))
{
char store[MAX_WORD];
NODE* new = NULL;
new = (NODE*)malloc(sizeof(NODE));
new->word=fgets(store, MAX_WORD, ptr);
new->next = NULL;
if (n == NULL)
{
n = new;
temp = n;
}
else
{
while (temp->next != NULL)
temp = temp->next;
temp->next = new;
}
}
fclose(ptr);
return n;
}
But if I implement the function that follows to print it, it prints random characters:
void printDictionary(NODO* dictionary)
{
NODO* temp = dictionary;
while (temp != NULL)
{
printf("\"%s\"\n", temp->word);
temp = temp->next;
}
}
Help please
i am writing a Dictionary using linked list in C, and all my functions work except my delete function, which is shown below along with all other necessary code. Every time i try to run my program as soon as it reaches a line in which it must delete a node, it gives me the error: Segmentation Fault (core dumped) which means it has something to do with the memory allocation or a null pointer i think. I know that the rest of my code works. All and any help is appreciated! :)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include"Dictionary.h"
// NodeObj
typedef struct NodeObj{
char* key;
char* value;
struct NodeObj* next;
} NodeObj;
// Node
typedef NodeObj* Node;
// newNode()
// constructor of the Node type
Node newNode(char* key, char* value)
{
Node N = malloc(sizeof(NodeObj));
assert(N!=NULL);
// if(key!=NULL && value!=NULL){
N->key = key;
N->value = value;
N->next = NULL;
// }
return(N);
}
// DictionaryObj
typedef struct DictionaryObj{
Node head;
int numItems;
} DictionaryObj;
// newDictionary()
// constructor for the Dictionary type
Dictionary newDictionary(void){
Dictionary D = malloc(sizeof(DictionaryObj));
assert(D!=NULL);
D->head = NULL;
D->numItems = 0;
return D;
}
Node findKey(Dictionary D, char*key){
Node N;
N = D->head;
while(N != NULL){
if(strcmp(N->key,key)==0){
return N;
}
N = N->next;
}
return NULL;
}
char* lookup(Dictionary D, char* k){
if(findKey(D, k)==NULL){
return NULL;
}else{
Node N;
N = findKey(D, k);
return N->value;
}
}
void delete(Dictionary D, char* k)
{
if(lookup(D,k) == NULL){
fprintf(stderr,
"KeyNotFoundException: Cannot delete non-existent key\n");
exit(EXIT_FAILURE);
}
int check = strcmp(D->head->key, k);
if(check == 1){
D->head = D->head->next;
return;
}
Node cur;
Node prev;
cur = D->head;
prev = NULL;
while( cur != NULL){
int ret1;
ret1 = strcmp(cur->key, k);
while( ret1 == 0){
prev = cur;
cur = cur->next;
}
}
prev->next = cur->next;
D->numItems--;
}
The NodeObject should store copy of the string and care for deleting it:
typedef struct Node Node;
struct Node {
Node *next;
char *key, *value;
};
Node* newNode(char* key, char* value) {
assert(key && value);
Node* node = (Node*)malloc(sizeof(Node));
assert(node);
node->next = NULL;
node->key = strdup(key);
node->value = strdup(value);
}
void delNode(Node* node) {
free(node->key);
free(node->value);
}
Consider using the original code (without that strdup) in this scenairo:
Node* prepare() {
char key_buf[20]; strcpy(key_buf, "mykey");
char val_buf[20]; strcpy(val_buf, "myval");
return newNode(key_buf, val_buf);
}
void examine(Node* node) {
printf("Node key=%s value=%s\n", node->key, node->value);
}
int main() {
examine(prepare());
}
the above code would crash because Node would have pointers to stack (in your case without that strdup), but key_buf+val_buf were only valid inside prepare() (garbage outside and therefore inside examine() - node->key points to random data).
Hii ,
i Was implementing a trie in C ... but i am getting an error in the insert_trie function .
I could not figure out why the root node is not getting updated . Please help me with this.
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct
{
char value;
int level;
struct node *next;
struct node *list;
}node;
node *trie = NULL;
node *init_trie()
{
node *new = (node *)malloc(sizeof(node));
if(trie == NULL)
{
new->value = '$';
new->next = NULL;
new->list = NULL;
new->level = 0;
trie = new;
printf("\n Finished initializing the trie with the value %c",trie->value);
return trie;
}
printf("\n Trie is already initialized");
return trie;
}
node *insert_trie(char *s)
{
node *nodepointer = trie;
node *new = (node *)malloc(sizeof(node));
node *save = NULL;
int i=0;
while(s[i]!=NULL)
{
nodepointer = nodepointer->list;
while(nodepointer!=NULL)
{
if(s[i] == nodepointer->value)
{
printf("\n Found %c",nodepointer->value);
nodepointer = nodepointer->list;
i++;
}
save = nodepointer;
nodepointer = nodepointer->next;
}
new->value = s[i];
new->next = NULL;
new->list = NULL;
printf("\n Inserting %c",new->value);
save->next = new;
i++;
}
return trie;
}
int main()
{
int num;
char *s = (char *)malloc(sizeof(char)*10);
trie = init_trie();
printf("\n Enter the number of words to enter into the trie ");
scanf("%d",&num);
while(num>0)
{
scanf("%s",s);
//printf("%s",s);
trie = insert_trie(s);
printf("\n Finished inserting the word %s into the trie \n",s);
num --;
}
return 0;
}
I get a segmentation fault due to the line nodepointer = nodepointer->list in insert_trie function ... Why ????
P.S : This is not homework.But i am trying to implement it. I just could not find the mistake .
"Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z."
I have written this very simple solution for the above question from LeetCode. It has passed all the 16 test cases from LeetCode. I hope this will help.
//node structure
struct TrieNode {
char value;
int count;
struct TrieNode * children[27];
};
static int count =0;
/** Initialize your data structure here. */
//return root pointer
struct TrieNode* trieCreate() {
struct TrieNode *pNode = NULL;
pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));
if (pNode)
{
pNode->value = '\0';
pNode->count =0;
memset(pNode->children, 0, sizeof(pNode->children));
}
return pNode;
}
/** Inserts a word into the trie. */
void insert(struct TrieNode* root, char* word) {
struct TrieNode *pCrawl = root;
count ++;
//check if the word is not empty
if(word){
int index=0, i =0;
//check if the root is not empty
if (root){
while( word[i] != '\0'){
index = ( (int) (word[i]) - (int)'a');
if(!pCrawl->children[index])
{
pCrawl->children[index] = trieCreate();
pCrawl->children[index]->value = word[i];
}
pCrawl = pCrawl->children[index];
i++;
}
//Count !=0 tell us that this is the last node;;
pCrawl->count = count;
}
}}
/** Returns if the word is in the trie. */
bool search(struct TrieNode * root, char* word) {
struct TrieNode *pCrawl = root;
bool flag = false;
//check if word is NULL
if(!word)
return false;
//if the trie is empty
if(!root)
{
return false;
}
//if word is empty
if (*word == '\0') {
return true;
}
int i=0, index =0 ;
while (word[i] != '\0')
{
index = ((int) (word[i]) - (int)'a');
//// if the node/character is not in Trie
if(!pCrawl->children[index])
{
flag = false;
break;
}
pCrawl = pCrawl->children[index];
i++;
}
//count != 0 marks node as last / leaf node
if(pCrawl->count != 0 && word[i] == '\0')
{
flag = true;
}
return flag;
}
/** Returns if there is any word in the trie
that starts with the given prefix. */
bool startsWith(struct TrieNode* root, char* prefix) {
struct TrieNode * pCrawl = root;
int i =0, index=0;
bool flag = false;
if(root){
while(prefix[i] != '\0')
{
index = ((int) (prefix[i]) - (int)'a');
if(pCrawl->children[index] == NULL){
flag = false;
return flag;
}
else
flag = true;
pCrawl = pCrawl->children[index];
i++;
}
}
return flag;
}
/** Deallocates memory previously allocated for the TrieNode. */
void trieFree(struct TrieNode* root) {
if(root){
for(int i = 0; i <=26; i ++)
{
trieFree(root->children[i]);
}
free(root);
}
}
// Your Trie object will be instantiated and called as such:
// struct TrieNode* node = trieCreate();
// insert(node, "somestring");
// search(node, "key");
// trieFree(node);
A trie holds one node per character and you're only performing one malloc per string. You should be calling malloc for every node. (Also, malloc.h is outdated. stdlib.h contains malloc since the ANSI C standard of 1989.)
node *insert_trie(char *s)
{
node *nodepointer = trie;
node *new = (node *)malloc(sizeof(node));
node *save = NULL;
int i=0;
while(s[i]!=NULL)
{
nodepointer = nodepointer->list;
while(nodepointer!=NULL)
{
if(s[i] == nodepointer->value)
{
printf("\n Found %c",nodepointer->value);
nodepointer = nodepointer->list; // Advance pointer once OK
i++;
}
save = nodepointer;
nodepointer = nodepointer->next; // Advance pointer without checking
}
new->value = s[i];
new->next = NULL;
new->list = NULL;
printf("\n Inserting %c",new->value);
save->next = new;
i++;
}
return trie;
}
Within the if test you advance nodepointer to nodepointer->list. Once the if test completes you advance nodepointer to nodepointer->next without checking if nodepointer is NULL from the advancement which occured within the if block.
Could someone direct me to some tutorial on Tree Data Structures using C. I tried googling but most implementations are for C++ or Java.If someone can point me to some online tutorials that are in C it would be great.
Thanks..
Generic tree-traversal methods: http://en.wikipedia.org/wiki/Tree_traversal (see right sidebar for a huge list of algorithms to choose from).
Some tutorials:
http://randu.org/tutorials/c/ads.php
http://www.ehow.com/how_2056293_create-binary-tree-c.html
Here's a bit of tutorial code from a couple of decades ago. In fact, it's been lying around so long, I don't remember where it came from or who wrote it (could have been me, but I'm really not sure). Theoretically it's a bit non-portable, using strdup, which isn't part of the standard library, though most compilers have/supply it.
/* Warning: untested code with no error checking included. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A tree node. Holds pointers to left and right sub-trees, and some data (a string).
*/
typedef struct node {
struct node *left;
struct node *right;
char *string;
} node;
node *root; /* pointers automatically initialized to NULL */
int insert(const char *string, node *root) {
/* Add a string to the tree. Keeps in order, ignores dupes.
*/
int num = strcmp(root->string, string);
node *temp;
for(;;) {
if ( 0 == num)
/* duplicate string - ignore it. */
return 1;
else if (-1 == num) {
/* create new node, insert as right sub-tree.
*/
if ( NULL == root -> right ) {
temp = malloc(sizeof(node));
temp -> left = NULL;
temp -> right = NULL;
temp -> string = strdup(string);
return 2;
}
else
root = root -> right;
}
else if ( NULL == root ->left ) {
/* create new node, insert as left sub-tree.
*/
temp = malloc(sizeof(node));
temp -> left = NULL;
temp -> right = NULL;
temp -> string = strdup(string);
return 2;
}
else
root = root -> left;
}
}
void print(node *root) {
/* in-order traversal -- first process left sub-tree.
*/
if ( root -> left != NULL )
print(root->left);
/* then process current node.
*/
fputs(root->string, stdout);
/* then process right sub-tree
*/
if ( root->right != NULL )
print(root->right);
}
int main() {
char line[100];
/* Let user enter some data. Enter an EOF (e.g., ctrl-D or F6) when done.
*/
while ( fgets(line, 100, stdin))
insert(line, root);
/* print out the data, in order
*/
print(root);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct binary_node {
struct binary_node *left;
struct binary_node *right; int value;
};
typedef struct binary_node NODE;
int search(NODE *temp, int data)
{
int found = 0;
#if 0
while (temp == NULL) {
if (temp->value == data) {
found = 1;
break;
}
else if (temp->value > data)
temp = temp->left;
else if (temp->value < data)
temp = temp->right;
}
return found;
#endif
if (temp == NULL)
return 0;
else if (temp->value == value)
return 1;
else if (temp->value > data)
return search(temp->left, data);
else if (temp->value < data)
}
NODE *del(NODE *root, int val)
{
if (root = NULL)
return ;
if (val < root->val)
root->left = delete(root->left, val);
else if (val > root->val)
root->right = delete(root->right, val);
else {
if (root->left == NULL && root->right == NULL) {
temp = root;
free(temp);
root = NULL;
}
else if (root->left == NULL) {
temp = root;
root = root->right;
free(temp);
}
else if (root->right == NULL) {
temp = root;
root = root->left;
free(temp);
}
else {
temp = min(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
}
return root;
}
NODE *insert_node(NODE *node, int val)
{
if (*node == NULL) {
node = (NODE *) malloc (sizeof(NODE));
node->left = NULL;
node->right = NULL;
node->value = val;
}
if (node->value > val)
node->left = insert_node(node->left, val);
else if (node->value < val)
node->right = insert_node(node->right, val);
else
printf("Discarding the data as it already exists in node\n");
return node;
}
}
int main()
{
NODE *root = NULL;
root = insert_node(root, 50);
insert_node(root, 4);
insert_node(root, 14);
insert_node(root, 44);
insert_node(root, 24);
insert_node(root, 34);
insert_node(root, 74);
insert_node(root, 54);
insert_node(root, 64);
print_order(&root);
search(&root, 34);
del(&root);
return 0;
}