I'm working on a delete function in my code. I want to delete the key, value pair within the node and free the space allocated to it. I'm not sure how to approach this so that the following nodes shift into the right place (not sure how to word it, hope you know what I mean). Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "symTable.h"
#define DEFAULT_TABLE_SIZE 61
#define HASH_MULTIPLIER 65599
/*Structures*/
typedef struct Node
{
char *key;
void *value;
struct Node *next;
} Node_T;
typedef struct SymTable
{
Node_T **Table;
int tablesize;
int counter;
} *SymTable_T;
/*Global Variables*/
int tablesize = DEFAULT_TABLE_SIZE;
int counter = 0;
/*Create function to show how memory is allocated*/
SymTable_T SymTable_create(void)
{
SymTable_T S_Table;
S_Table = malloc(sizeof(SymTable_T *) * DEFAULT_TABLE_SIZE);
S_Table->Table = (Node_T **) calloc(DEFAULT_TABLE_SIZE, sizeof(Node_T *));
return S_Table;
}
/*Hash Function*/
static unsigned int hash(const char *key, const int tablesize)
{
int i;
unsigned int h = 0U;
for (i = 0; key[i] != '\0'; i++)
h = h * tablesize + (unsigned char) key[i];
return h % tablesize;
}
/*Delete Function*/
int symTable_delete(SymTable_T symTable, const char *key)
{
Node_T *new_list;
unsigned int hashval = hash(key, DEFAULT_TABLE_SIZE);
free(new_list->key);
free(new_list->value);
//here is where I am stuck, how can I make it so the nodes following the one deleted go to the right space?
}
With a singly linked list you have
A -> B -> C
if you want to remove B then you need to make
A -> C
The only way to do this is to get the parent of B and update its pointer which means either
You need to add a pointer from a node to its parent ( aka use a doubly linked list )
You iterate over the list until you find a node where the child pointer is set to the node you are removing and then you update the pointer to instead point to child.child
Related
I'm trying to solve this codewars kata
Basically I need to wite a programe that spits out an array/list of numbers from a perticular range (of numbers) which have k primes multiplicatively.
countKprimes(5, 500, 600) --> [500, 520, 552, 567, 588, 592, 594]
Now my program "works" as in it can print the results correctly, but if I put it in codewars' answer area (without main of course), it just runs forever.
"Error code SIGKILL : Process was terminated. It took longer than 12000ms to complete"
This is the codewars template
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// In the preloaded section are some functions that can help.
// They can be used as a small library.
// There is no file to include, only the templates below.
struct node {
int data;
struct node *next;
};
struct list {
size_t sz;
struct node *head;
};
struct list* createList();
// push data at the head of the list
void insertFirst(struct list* l, int data);
struct list* reverse(struct list* l);
void listFree(struct list* l);
// functions to write
struct list* kPrimes(int k, int start, int nd)
{
// your code
}
And this is my code
#include <stdio.h>
struct list{
int a[600];
};
int smallestPrimeFactor(int number){
int x;
for(x = 2; x < number; x++) {
if(number % x == 0) {
return x;
}
}
return number;
}
int primefactors(int ofnumber){
static int counter = 0;
int tempcounter = counter;
int nextnumber = ofnumber/smallestPrimeFactor(ofnumber);
if(nextnumber != 1) {
if(ofnumber >= nextnumber) {
counter++;
primefactors(nextnumber);
}
}
return (counter - tempcounter) + 1;
}
struct list kPrimes(int k, int start, int nd){
int x, g = 0;
struct list ls;
for(x = start; x < nd; x++){
if(primefactors(x) == k){
ls.a[g] = x;
g++;
}
}
return ls;
}
int main(int argc, int **argv){
int p = 5, s = 500, e = 600;
int j = 0;
while(kPrimes(p, s, e).a[j] != '\0'){
printf("%d\n", kPrimes(p, s, e).a[j]);
j++;
}
}
I think the culprit here is
struct list{
int a[600];
};
Maybe while reading the array, the test file is overshooting a's index past '\0'.
I thought of a way of solving that by making a a pointer to integer but doing int *a; prints out nothing.
I know there are more than one way of returning an array. Using referance, using a static array, passing an array as argument, etc. But I want to solve this codewars' way. Think it'll be a nice learning experience.
So, how should I be using
struct node {
int data;
struct node *next;
};
struct list {
size_t sz;
struct node *head;
};
to solve the problem?
You should not bother about the structure themselves, you should simply use the provided functions:
struct list* kPrimes(int k, int start, int nd){
int x, g = 0;
struct list *ls = createList(); // 1. Create the list.
// 2. Maybe check if ls != NULL...
for(x = start; x < nd; x++){
if(primefactors(x) == k){
insertFirst(ls, x); // 3. Insert at the beginning.
g++;
}
}
struct list *rls = reverse(ls); // 4. Reverse the list.
listFree(ls); // 5. Free the original list.
return rls; // 6. Return the reversed list.
}
Since the functions reverse is not documented, I can only guess that it creates a new list without modifying the old one, which is why you need to free it after.
The createList(), insertFirst(), reverse(), and listFree() functions, as well as the function that consumes the return value of your function are all provided to you, and they all work with the types struct list and struct node. How, then, do you imagine it could work if you try to use a differently-defined struct list than those existing functions use?
So yes, you should be using the struct node and struct list types provided to you -- and the handy functions for manipulating them -- rather than defining different structure types with the same tags.
I have to make a list that arrange the people in decreasing order of their number('no' for my program). I tryed to make it by modifying the addNode function but I got no result(peoples do not arrange by their number). This is my code:
Header code:
#ifndef __EX__
#define __EX__
typedef struct Person{
char name[10];
float no;
struct Person *pNext;
} NODE, *pNODE, **ppNODE;
void addNode(ppNODE, pNODE);
void travers(pNODE, unsigned int*);
#endif
Functions folder:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include "EX.h"
void addNode (ppNODE ppPrim, pNODE p){
pNODE q = (pNODE)malloc(sizeof(NODE));
assert(q!=NULL);
printf("Add name: \n");
scanf("%s", &q->name);
printf("\nAdd no: ");
scanf("%f", &q->no);
if (p == NULL || q->no < p->no) {
q->pNext = *ppPrim;
*ppPrim = q;
} else {
q->pNext = p->pNext;
p->pNext = q;
}
return;
}
void travers(pNODE pPrim, unsigned int *pLen){
*pLen = 0;
pNODE tmp = pPrim;
while (tmp != NULL){
puts (tmp->name);
fprintf(stdout, " no %.2f\n", tmp->no);
tmp = tmp->pNext;
(*pLen)++;
}
return;
}
Main folder:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include "EX.h"
int main(){
unsigned int len;
pNODE prim = NULL;
int i;
for (i=0; i<=1; i++){
addNode(&prim, prim);
addNode(&prim, prim->pNext);
}
travers(prim, &len);
return 0;
}
When you insert a new node to the list, you must traverse the list until you find a suitable place to insert it. Your code takes a second argument, which isn't really needed and causes confusion, and only looks at that.
The code to insert a code q at the end of a list that is defined by its head is:
Node *prev = NULL;
Node *p = *head;
while (p) {
prev = p;
p = p->pNext;
}
q->pNext = p;
if (prev == NULL) {
*head = q;
} else {
prev->pNext = q;
}
You can get rid of keeping track of the previous node and the distinction between inserting at the head and inserting after that by traversing the list with a pointer to node pointer:
Node **p = &head;
while (*p && (*p)->no < q->no) {
p = &(*p)->pNext;
}
q->pNext = *p;
*p = q;
In this concise code, p holds the address of the head at first and the address of the pNext pointer of the previous node. Both can be updated via *p.
You can now use this code to traverse only as far as the numbers associated with each node are smaller than the one of the node to insert. here's a complete program:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct Node Node;
void addNode(Node **p, const char *name, float no);
void travers(Node *pPrim, unsigned int *pLen);
struct Node {
char name[10];
float no;
Node *pNext;
};
void addNode(Node **p, const char *name, float no)
{
Node *q = malloc(sizeof(*q));
assert(q != NULL);
snprintf(q->name, sizeof(q->name), "%s", name);
q->no = no;
while (*p && (*p)->no < q->no) {
p = &(*p)->pNext;
}
q->pNext = *p;
*p = q;
}
void traverse(const Node *pPrim, unsigned int *pLen)
{
*pLen = 0;
while (pPrim != NULL) {
fprintf(stdout, "%-12s%.2f\n", pPrim->name, pPrim->no);
pPrim = pPrim->pNext;
(*pLen)++;
}
}
int main()
{
unsigned int len;
Node *prim = NULL;
addNode(&prim, "Alice", 0.23);
addNode(&prim, "Bob", 0.08);
addNode(&prim, "Charlie", 0.64);
addNode(&prim, "Dora", 0.82);
traverse(prim, &len);
printf("\n%u entries.\n", len);
return 0;
}
Things to node:
I've used Node * and Node ** instead of the typedeffed pNODE and ppNODE. In my opinion using the C pointer syntax is clearer.
You should separate taking user input from adding a node.
In your code you shouldn't pass the address of the char array when scanning a string, just the char array. (It happens to work, but it isn't correct. The compiler should warn you about that.)
I have a problem to sort an array (dynamically allocated) in a structure. Firstly, the idea was to order the array i in the structure in an ascendant order. Then I was thinking to order the array i maintaining instead the array j with the same "relationship" obtained when it was constructed the initial structure. I try to work for the first idea, but without any result with qsort.So this is my code... Any ideas? I think there is a problem in the construction of the comparing function..
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int M =10;
int N =30;
int K = 10;
struct element {
int *i;
int *j;
int k;
};
struct element *create_structure();
void print_element(struct element *);
int compare (const void *, const void * );
struct element * sort(struct element *);
main()
{
srand(time(NULL));
struct element *lista;
int count;
lista=create_structure();
print_element(lista);
printf("\n");
lista=sort(lista);
}
struct element *create_structure()
{
int aux1,aux2,count,load;
struct element *structure;
structure = (struct element *) malloc (M*sizeof(struct element *));
structure->k=K;
structure->i= (int *)malloc(structure->k*sizeof(int));
structure->j=(int *)malloc (structure->k*sizeof(int));
for (count = 0; count < K; count ++)
{
aux1=rand()%N;
(structure->i)[count]=aux1;
do
{
aux2=rand()%N;
}while(aux2==aux1);
(structure->j)[count]=aux2;
}
return (structure);
}
void print_element(struct element *lista)
{
int count;
for(count = 0; count < K; count ++)
{
printf("%d %d\n",lista->i[count],lista->j[count]);
}
}
int compare(const void *a, const void *b)
{
struct element *ia = (struct element *)a;
struct element *ib = (struct element *)b;
int *ptr1=(ia->i);
int *ptr2=(ib->i);
return (*ptr1-*ptr2);
}
struct element * sort(struct element *list)
{
qsort(list, sizeof(list->i)/ sizeof(int) , sizeof(list->i), compare);
//qsort(list->i, K, sizeof(list->i), compare);
print_element(list);
return (list);
}
Sorry for being late to the party ! :)
So let's start first by mentioning the wrong statements in your code
>> First
in function create_structure() you want to allocate memory for your structure pointer
struct element *structure; // here your structure pointer is
//pointing to memory space of type struct element
structure = (struct element *) malloc (M*sizeof(struct element *));
|------------------------|
|
V
Here you are allocating memory space of type struct element* which is
wrong ! instead it must be sizeof(struct element)
Concerning the while loop in the same function I found that it is totally useless
aux1=rand()%N;
(structure->i)[count]=aux1; // the value is in aux1 variable
do
{
aux2=rand()%N;
}while(aux2==aux1); // the loop try to get the same value of aux1
// or you have just stored it in aux1
(structure->j)[count]=aux2; // it is easy to delete the while loop and
// change aux2 by aux1
>> Second
Concerning the sort
qsort(list, sizeof(list->i)/ sizeof(int) , sizeof(list->i), compare);
|-----|
|
V
It is not an adress of the array so it is Wrong !
after knowing the major problems here is a version of code based on your own code which works perfectly
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int M =10;
int N =30;
int K = 10;
struct element {
int *i;
int *j;
int k;
};
struct element *create_structure();
void print_element(struct element *);
int compare (const void *, const void * );
void sort(struct element *); // changed the return value of sort
// to void as the argument will be changed directly because it is a
// pointer
int main()
{
srand(time(NULL));
struct element *lista;
lista=create_structure();
printf("\n--------- i --- j ---------\n\n");
print_element(lista);
printf("\n---------------------------\n");
sort(lista);
print_element(lista);
return 0;
}
struct element *create_structure()
{
int aux1=0,count=0;
struct element *structure;
// Changed the allocation of structure pointer
structure = (struct element *) malloc (sizeof(struct element));
structure->k=K;
structure->i= (int *)malloc(K*sizeof(int));
structure->j=(int *)malloc (K*sizeof(int));
for (count = 0; count < K; count ++)
{
aux1=rand()%N;
// we kept only the first aux1 and copied it in the two arrays
(structure->i)[count]=aux1;
(structure->j)[count]=aux1;
}
return (structure);
}
void print_element(struct element *lista)
{
int count=0;
for(count = 0; count < K; count++)
{
printf("row=%2d : %2d %2d\n",count+1,(lista->i)[count],(lista->j)[count]);
}
}
int compare(const void *a, const void *b)
{
// compare the values of two case of array pointed by i of type int
return *(int*)a-*(int*)b;
}
void sort(struct element *list)
{
// we will sort the array pointed by i which contains K elements
// of type int and size sizeof(int) by using the compare function
qsort(list->i, K , sizeof(int), compare);
}
Hope it helps ! :)
Note: Using this code in codeblocks v13.12 generates under linux (gcc version 4.8.2) wrong output !! [ It might be a BUG in Code::Blocks]
but using it with command line with gcc gives correct output !!
Basically I have to store words in linked list with each character having its own node. I get really confused with nested structures. How do I go to the next node? I know i'm doing this completely wrong which is why I'm asking.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char letter;
}NODE;
typedef struct handle
{
NODE **arr;
}HANDLE;
HANDLE * create();
void insert(handle **, char, int);
int main(int argc, char **argv)
{
FILE *myFile;
HANDLE *table = (HANDLE *)malloc(sizeof(HANDLE));
NODE *linked = (NODE *)malloc(sizeof(NODE));
int counter = 0;
linked = NULL;
table->arr[0] = linked;
char c;
myFile = fopen(argv[argc], "r");
while((c = fgetc(myFile)) != EOF)
{
if(c != '\n')
insert(&table, c, counter);
else
{
counter++;
continue;
}
}
}
void insert(HANDLE **table, char c, int x)
{
(*table)->arr[x]->letter = c; //confused on what to do after this or if this
//is even correct...
}
You have a linked list of words with each word being a linked list of characters. Am I right? If so, it is better to use the names for what they are:
typedef struct char_list
{
char letter;
struct char_list * next;
} word_t;
typedef struct word_list
{
word_t * word;
struct word_list_t * next;
} word_list_t;
Now, you can populate the lists as per need.
For a linked-list, you typically have a link to the next node in the node structure itself.
typedef struct node
{
char letter;
struct node *next;
}NODE;
Then from any given node NODE *n, the next node is n->next (if not NULL).
insert should scan the list until it finds an n->next that is NULL, and allocate a new node at the end (make sure to set its next to NULL).
You may want to have a function to initialize a new list given the table index, and a separate function to initialize a new node.
So I'm attempting to implement a hash table that will hash structures containing words.
the structures will be similar to this:
#ifndef HASHTABLE_H
#def HASHTABLE_H
typedef int (*HashFunctionT) (char* string, int upperbound);
struct node_
{
char * word;
struct node * next;
}
typedef struct node_ * node;
struct nodehash_
{
int size;
struct node * hash[100];
}
typedef struct nodehash_ * nodehash;
Hashtable createHashTable();
void addtohash(node list, nodehash hash);
#endif
And I want the hash function to work something like this:
#include "hashtable.h"
int hashFunction(char *word, int hashTableSize)
{
int length = strlen(word);
int h = 0;
int i;
for(i = 0; i<length; i++)
{
h=31 *h + word[i];
}
return h % hashTableSize;
};
nodehash createHashtable()
{
nodehash hashtable;
hashtable = malloc(sizeof(struct nodehash_));
hashtable->size = 100;
hashtable->hash = malloc(100 * sizeof (node));
int i;
for (i = 0; i < hashtable->size; i++)
{
hashtable->table[i] = NULL;
}
return hashtable;
};
void addtohash(node list, nodehash hashtable)
{
int nodehashnumber;
nodehashnumber = hashfunction(list->word, hash->size);
hashtable->hash[nodehasnumber] = list;
};
And the main functio will look something like this (assume that the linked list of node structures has been created and filled).
int main()
{
nodehash hashtable = createhashtable();
node nodelist;
/* here the nodelist would be created and filled and such and such*/
while (nodelist->next != NULL)
{
addtohash(nodelist, hashtable);
}
return;
}
Assume that there can be no collisions, because every word to be hashed will be different.
BAsically, I'm wondering if I missed and glaring, obvious mistakes or flaws in logic.
Any help would be greatly appreciated.
Thanks.
I didn't give the code an extensive read, but the first thing that stood out pretty clearly is the hash table size, 100. It is best to use a prime number for the size of your hash tables to help avoid collisions.
You seem to have a problem with semicolons:
struct node_
{
char * word;
struct node * next;
} /* <<-- HERE */
typedef struct node_ * node;
But::
int hashFunction(char *word, int hashTableSize)
{
int length = strlen(word);
int h = 0;
int i;
for(i = 0; i<length; i++)
{
h=31 *h + word[i];
}
return h % hashTableSize;
}; /* <<-- NOT here */
Also, a wise advice is IMHO to use as many unsigned types as possible: for the hash value (what does modulo division do with a negative operand?) and for sizes and indexes.
Rule of thumb: if it can not be negative: it's unsigned.