How to create AVL - c

I enter several numbers(2,1,4,5,9,3,6,7),after I enter the number '3', there something wrong,the function can not return correctly.
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode
{
int data;
int height;
struct AVLNode *LChild;
struct AVLNode *RChild;
}*AVLTree;
typedef struct AVLNode *Position;
static int Height(Position T)
{
if (T == NULL)
return -1;
else
return T->height;
}
static Position SingleLeft(Position k2)
{
Position k1;
k1 = k2->LChild;
k2->LChild = k1->RChild;
k1->RChild = k2;
k2->height = max(Height(k2->LChild), Height(k2->RChild)) + 1;
k1->height = max(Height(k1->LChild), Height(k1->RChild)) + 1;
return k1;
}
static Position SingleRight(Position k1)
{
Position k2;
k2 = k1->RChild;
k1->RChild = k2->LChild;
k2->LChild = k1;
k1->height = max(Height(k1->LChild), Height(k1->RChild)) + 1;
k2->height = max(Height(k2->LChild), Height(k2->RChild)) + 1;
return k2;
}
static Position DoubleLeft(Position k3)
{
k3->LChild = SingleRight(k3->LChild);
return SingleLeft(k3);
}
static Position DoubleRight(Position k1)
{
k1->RChild = SingleLeft(k1->RChild);
return SingleRight(k1);
}
void PrePrint(AVLTree T)
{
if (T != NULL)
{
printf("%d ", T->data);
PrePrint(T->LChild);
PrePrint(T->RChild);
}
}
AVLTree Insert(int x, AVLTree T)
{
if (T == NULL)
{
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->data = x;
T->LChild = T->RChild = NULL;
}
else if (x < T->data)
{
T->LChild = Insert(x, T->LChild);
if (Height(T->LChild) - Height(T->RChild) == 2)
{
if (x<T->LChild->data)
T = SingleLeft(T);
else
T = DoubleLeft(T);
}
}
else if (x > T->data)
{
T->RChild = Insert(x, T->RChild);
if (Height(T->RChild) - Height(T->LChild) == 2)
{
if (x>T->RChild->data)
T = SingleRight(T);
else
T = DoubleRight(T);
}
}
T->height = max(Height(T->LChild), Height(T->RChild)) + 1;
return T;
}
I think there is something wrong in my main function, I think I shouldn't write
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->LChild = T->RChild = NULL;
those code in mian function, I try to add a 'Init' function, but it doesn't work. It always said "'T' is being used without initialized"
int main()
{
AVLTree T;
T=(AVLTree)malloc(sizeof(struct AVLNode));I think there is wrong
T->LChild = T->RChild = NULL;
int x;
printf("please enter the data(0 to quit):");
scanf("%d", &x);
T->data = x;
while (x != 0)
{
Insert(x, T);
printf("enter a number(0 to quit):");
scanf("%d", &x);
}
PrePrint(T);
}

When your insertion makes a new root node, this fact is not propagated back to main in any way. The value of T inside the Insert function changes, but main has its own variable called T that isn't changed, and that's the one that you then use to print out the tree.
I notice that your Insert function returns an AVLTree, but when main calls it it doesn't do anything with the return value.
(This is not the only thing that's amiss in your code, but it would be a good place to start.)

Related

Binary searching in tree

I need to create this tree:
the tree
I need to implement a function that takes the tree's node (root), a number, and returns how many times the binary representation of the number occurs in the tree.
For example:
9(1001) occurs 4 times
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct TreeNode {
int val;
struct TreeNode* leftNode;
struct TreeNode* rightNode;
};
void strrev(char * arr, int start, int end) {
char temp;
if (start >= end) {
return;
}
temp = * (arr + start);
*(arr + start) = * (arr + end);
*(arr + end) = temp;
start++;
end--;
strrev(arr, start, end);
}
char * itoa(int number, char * arr, int base) {
int i = 0, r, negative = 0;
if (number == 0) {
arr[i] = '0';
arr[i + 1] = '\0';
return arr;
}
if (number < 0 && base == 10) {
number *= -1;
negative = 1;
}
while (number != 0) {
r = number % base;
arr[i] = (r > 9) ? (r - 10) + 'a' : r + '0';
i++;
number /= base;
}
if (negative) {
arr[i] = '-';
i++;
}
strrev(arr, 0, i - 1);
arr[i] = '\0';
return arr;
}
int count_occurrences(struct TreeNode* root, int number) {
int count = 0;
char binary[33];
itoa(number, binary, 2);
int length = strlen(binary);
struct TreeNode* current = root;
for (int i = 0; i < length; i++) {
if (binary[i] == '0') {
if (current->leftNode != NULL) {
current = current->leftNode;
} else {
return count;
}
} else {
if (current->rightNode != NULL) {
current = current->rightNode;
} else {
return count;
}
}
if (current->val == number) {
count++;
}
}
return count;
}
struct TreeNode* createNode(int value) {
struct TreeNode* newNode = malloc(sizeof(struct TreeNode));
newNode->val = value;
newNode->leftNode = NULL;
newNode->rightNode = NULL;
return newNode;
}
struct TreeNode* insertLeftNode(struct TreeNode* rootNode, int value) {
rootNode->leftNode = createNode(value);
return rootNode->leftNode;
}
struct TreeNode* insertRightNode(struct TreeNode* rootNode, int value) {
rootNode->rightNode = createNode(value);
return rootNode->rightNode;
}
int main() {
struct TreeNode* rootNode = createNode(1);
insertLeftNode(rootNode, 1);
insertRightNode(rootNode, 0);
insertLeftNode(rootNode->leftNode, 0);
insertRightNode(rootNode->leftNode, 1);
insertLeftNode(rootNode->rightNode, 0);
insertRightNode(rootNode->rightNode, 0);
insertLeftNode(rootNode->leftNode->leftNode, 0);
insertRightNode(rootNode->leftNode->leftNode, 0);
insertLeftNode(rootNode->rightNode->rightNode, 0);
insertRightNode(rootNode->rightNode->rightNode, 0);
printf("\n%d", count_occurrences(rootNode, 9));
}
I am using itoa(), but for some reasons it doesn't return nothing.
Itoa gave compiler warning so i copied it from internet.
Also I think i am not correctly creating the tree.

What can I do to make my code generate an output?

#include <stdio.h>
#include <stdlib.h>
typedef enum TypeTag {
ADD,
SUB,
MUL,
DIV,
ABS,
FIB,
} TypeTag;
typedef struct Node {
TypeTag type;
int value;
struct Node *left;
struct Node *right;
} Node;
#define MAXN 100
int fib[MAXN];
// function to create a new node
Node* makeFunc(TypeTag type) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->type = type;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// fibonacci function using dynamic programming
int fibonacci(int n) {
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
// function to calculate the value of a node
int calc(Node* node) {
if (node->type == ADD) {
return calc(node->left) + calc(node->right);
}
else if (node->type == SUB) {
return calc(node->left) - calc(node->right);
}
else if (node->type == MUL) {
return calc(node->left) * calc(node->right);
}
else if (node->type == DIV) {
return calc(node->left) / calc(node->right);
}
else if (node->type == ABS) {
return abs(calc(node->left));
}
else if (node->type == FIB) {
return fibonacci(calc(node->left));
}
return node->value;
}
int main() {
for (int i = 0; i < MAXN; i++) {
fib[i] = -1;
}
Node *add = makeFunc(ADD);
add->left = makeFunc(10);
add->right = makeFunc(6);
Node *mul = makeFunc(MUL);
mul->left = makeFunc(5);
mul->right = makeFunc(4);
Node *sub = makeFunc(SUB);
sub->left = makeFunc(calc(add));
sub->right = makeFunc(calc(sub));
Node *fibo = makeFunc(FIB);
fibo->left = makeFunc(abs(calc(sub)));
fibo->value = fibonacci(calc(fibo->left));
printf("add : %d\n", calc(add));
printf("mul : %d\n", calc(mul));
printf("sub : %d\n", calc(sub));
printf("fibo : %d\n", calc(fibo));
printf("Hello world");
// return 0;
}
I think the problem is coming from the makeFunc function but i am not sure what else to do.I tried to print hello world to see if the problem is from my implementations but it still did not print.
I was trying to solve this problem
{
TypeTag type;
} Node;
typedef enum TypeTag {
...
}
Using this structure, please write a function that returns fibonacci sequence based on the following arithmetic operations (+, -,
*, /) and conditions. The fibonacci function should be implemented using Dynamic Programming.
main()
{
Node *add = (*makeFunc(ADD))(10, 6);
Node *mul = (*makeFunc(MUL))(5, 4);
Node *sub = (*makeFunc(SUB))(mul, add);
Node *fibo = (*makeFunc(SUB))(sub, NULL);
calc(add);
calc(mul);
calc(sub);
calc(fibo)
}
Output
add : 16
mul : 20
sub : -4
fibo : 2
You can't use makeFunc(4) to make the representation of the number 4, because 4 == ABS. You should use a separate type for nodes that represent numbers rather than functions. Then use another function to create nodes of this type.
Another problem is here:
sub->right = makeFunc(calc(sub));
You can't call calc(sub) until after you've filled in both sub->left and sub->right. I'm guessing you meant to use calc(mul).
#include <stdio.h>
#include <stdlib.h>
typedef enum TypeTag {
ADD,
SUB,
MUL,
DIV,
ABS,
FIB,
LIT
} TypeTag;
typedef struct Node {
TypeTag type;
int value;
struct Node *left;
struct Node *right;
} Node;
#define MAXN 100
int fib[MAXN];
// function to create a new node
Node* makeFunc(TypeTag type) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->type = type;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node* makeValue(int value) {
Node *newNode = makeFunc(LIT);
newNode->value = value;
return newNode;
}
// fibonacci function using dynamic programming
int fibonacci(int n) {
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
// function to calculate the value of a node
int calc(Node* node) {
if (node->type == ADD) {
return calc(node->left) + calc(node->right);
}
else if (node->type == SUB) {
return calc(node->left) - calc(node->right);
}
else if (node->type == MUL) {
return calc(node->left) * calc(node->right);
}
else if (node->type == DIV) {
return calc(node->left) / calc(node->right);
}
else if (node->type == ABS) {
return abs(calc(node->left));
}
else if (node->type == FIB) {
return fibonacci(calc(node->left));
}
else if (node->type == LIT) {
return node->value;
}
printf("Invalid node type %d\n", node->type);
exit(1);
}
int main() {
for (int i = 0; i < MAXN; i++) {
fib[i] = -1;
}
Node *add = makeFunc(ADD);
add->left = makeValue(10);
add->right = makeValue(6);
Node *mul = makeFunc(MUL);
mul->left = makeValue(5);
mul->right = makeValue(4);
Node *sub = makeFunc(SUB);
sub->left = makeValue(calc(add));
sub->right = makeValue(calc(mul));
Node *fibo = makeFunc(FIB);
fibo->left = makeValue(abs(calc(sub)));
fibo->value = fibonacci(calc(fibo->left));
printf("add : %d\n", calc(add));
printf("mul : %d\n", calc(mul));
printf("sub : %d\n", calc(sub));
printf("fibo : %d\n", calc(fibo));
printf("Hello world\n");
// return 0;
}

How to remove necessary nodes from a binary tree?

Good evening forum members.
The following is on the agenda:
Read a sequence of coordinates (x, y, z) of spatial points from the file, ordered by distance from the point of origin (develop a separate function for calculating the distance and store this value in the data structure);
To bypass use the bottom option from right to left;
Extract from the tree all nodes whose z coordinate falls within the specified range zmin ..zmax (I decided to take from 7 to 14) and indicate their number;
To completely erase the tree, use the direct (from the root) version of the bypass from left to right;
Print the entire tree using a non-recursive function.
Please help with number 3. It is not possible to implement the deletion algorithm according to a given condition. It either does not work at all, or errors arrive (
Thanks in advance to everyone who responds
CODE:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_LEN 8
#define STACK_INIT_SIZE 20
typedef struct Tree {
int z;
int viddal;
struct Tree* left, * right;
} TREE;
typedef struct Stack {
size_t size, limit;
TREE** data;
} STACK;
int Distance(FILE* ftxt, int* vid, int* z_cord);
int CreateTreeFromFile(void);
TREE* NewNode(FILE* f, int viddal, int z);
void AddNewNode(TREE* pnew);
void PrintTreeNIZ(TREE* proot);
void iterPostorder(TREE* root);
void OutputTreeStructure(const char* title);
void ShowTree(TREE* proot, int level);
void ShowLevels(void);
int TreeHeight(TREE* proot);
void EraseTree(TREE* proot);
void DeleteSomeNodes(void);
int DeleteNode(TREE* pnew_adr);
TREE* root;
int main(){
system("chcp 1251");
if (CreateTreeFromFile() == 0)
return 0;
puts("\n Created tree: ");
PrintTreeNIZ(root);
OutputTreeStructure("of created tree");
DeleteSomeNodes();
OutputTreeStructure("of the new tree");
EraseTree(root);
root = NULL;
puts("\n Tree was deleted from DM\n\n");
return 0;
}
int Distance(FILE* ftxt, int *vid, int* z_cord) {
TREE* pel = (TREE*)malloc(sizeof(TREE));
if (feof(ftxt)) {;
return NULL;
}
else {
int x, y, z;
fscanf(ftxt, "%d%d%d", &x, &y, &z);
*z_cord = z;
*vid = sqrt(x * x + y * y + z * z);
}
}
int CreateTreeFromFile()
{
const char* fname = "Cords_1.txt";
FILE* fvoc = fopen(fname, "r");
if (fvoc == NULL) {
printf("\n\t\tCan`t open file %s...\n", fname);
return 0;
}
TREE* node;
int viddal, z;
Distance(fvoc, &viddal, &z);
while ((node = NewNode(fvoc, viddal, z)) != NULL) {
AddNewNode(node);
Distance(fvoc, &viddal, &z);
}
fclose(fvoc);
return 1;
}
TREE* NewNode(FILE* f, int viddal, int z)
{
TREE* pel;
pel = (TREE*)malloc(sizeof(TREE));
if (feof(f)) {
return NULL;
}
pel->viddal = viddal;
pel->z = z;
pel->left = pel->right = NULL;
return pel;
}
void AddNewNode(TREE* pnew) {
if (root == NULL) {
root = pnew;
return;
}
TREE* prnt = root;
do {
if (pnew->viddal == prnt->viddal) {
free(pnew);
return;
}
if (pnew->viddal < prnt->viddal) {
if (prnt->left == NULL) {
prnt->left = pnew;
return;
}
else
prnt = prnt->left;
}
else {
if (prnt->right == NULL) {
prnt->right = pnew;
return;
}
else
prnt = prnt->right;
}
} while (1);
}
void PrintTreeNIZ(TREE* proot)
{
if (proot == NULL)
return;
printf("\n Right Tree");
iterPostorder(proot->right);
printf("\n\n Left Tree");
iterPostorder(proot->left);
printf("\n\n Korin - %d", proot->viddal);
}
void OutputTreeStructure(const char* title)
{
printf("\n\n\n Structur%s:\n\n", title);
ShowLevels();
ShowTree(root, 0);
puts("\n");
}
#define TAB 7
void ShowTree(TREE* proot, int level)
{
if (proot == NULL) return;
ShowTree(proot->right, level + 1);
printf("\n%*c%d", level * TAB + 10, ' ', proot->viddal);
ShowTree(proot->left, level + 1);
}
void ShowLevels(void)
{
int lev;
printf(" Level: ");
for (lev = 1; lev <= TreeHeight(root); lev++)
printf(" %-*d", 6, lev);
printf("\n\n");
}
int TreeHeight(TREE* proot)
{
int lh, rh;
if (proot == NULL) return 0;
lh = TreeHeight(proot->left);
rh = TreeHeight(proot->right);
return lh > rh ? lh + 1 : rh + 1;
}
void EraseTree(TREE* proot)
{
if (proot == NULL)
return;
EraseTree(proot->left);
EraseTree(proot->right);
free(proot);
}
STACK* createStack() {
Stack* tmp = (Stack*)malloc(sizeof(Stack));
tmp->limit = STACK_INIT_SIZE;
tmp->size = 0;
tmp->data = (TREE**)malloc(tmp->limit * sizeof(TREE*));
return tmp;
}
void freeStack(Stack** s) {
free((*s)->data);
free(*s);
*s = NULL;
}
void push(Stack* s, TREE* item) {
if (s->size >= s->limit) {
s->limit *= 2;
s->data = (TREE**)realloc(s->data, s->limit * sizeof(TREE*));
}
s->data[s->size++] = item;
}
TREE* pop(Stack* s) {
if (s->size == 0) {
exit(7);
}
s->size--;
return s->data[s->size];
}
TREE* peek(Stack* s) {
return s->data[s->size - 1];
}
void iterPostorder(TREE* root) {
Stack* ps = createStack();
TREE* lnp = NULL;
TREE* peekn = NULL;
while (!ps->size == 0 || root != NULL) {
if (root) {
push(ps, root);
root = root->left;
}
else {
peekn = peek(ps);
if (peekn->right && lnp != peekn->right) {
root = peekn->right;
}
else {
pop(ps);
printf("\n\t Visited -> %d", peekn->viddal);
lnp = peekn;
}
}
}
freeStack(&ps);
}
// HELP WITH THAT
//--------------------------------------------------------------------------------------------
void DeleteSomeNodes(void)
{
printf("\n\t Deleting needing nods:\n");
TREE* pfind = (TREE*)malloc(sizeof(TREE));
do {
if (pfind->z >= 7 && pfind->z <= 14) {
DeleteNode(root);
printf(" Number %d was deleted from tree\n", root);
}
} while (1);
puts("\n\n");
}
#define NoSubTree 0
#define LeftSubTree -1
#define RightSubTree 1
#define TwoSubTrees 2
int DeleteNode(TREE* pnew_adr)
{
TREE* proot = root;
int subtr;
if (proot == NULL) return 0;
if (pnew_adr->viddal < proot->viddal)
return DeleteNode(proot->left);
if (pnew_adr->viddal > proot->viddal)
return DeleteNode(proot->right);
if (proot->left == NULL && proot->right == NULL)
subtr = NoSubTree;
else if (proot->left == NULL)
subtr = RightSubTree;
else if (proot->right == NULL)
subtr = LeftSubTree;
else
subtr = TwoSubTrees;
switch (subtr) {
case NoSubTree:
root = NULL; break;
case LeftSubTree:
root = proot->left; break;
case RightSubTree:
root = proot->right; break;
case TwoSubTrees:
TREE* pnew_root = proot->right, * pnew_prnt = proot;
while (pnew_root->left != NULL) {
pnew_prnt = pnew_root;
pnew_root = pnew_root->left;
}
pnew_root->left = proot->left;
if (pnew_root != proot->right) {
pnew_prnt->left = pnew_root->right;
pnew_root->right = proot->right;
}
root = pnew_root;
}
free(proot);
return 1;
}
//--------------------------------------------------------------------------------------------

Why is my Hash Map insert function not working?

I am making a Hash Map with people's names as its key using C language. I am using separate chaining to resolve the collision.
This is my code:
#include<stdio.h>
#include<stdlib.h>
#define MinTableSize 1
#include <stdbool.h>
//Colission resolution Using linked list
struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;
typedef unsigned int Index;
Index Hash(const char *Key, int Tablesize)
{
unsigned int HashVal = 0;
while(*Key != '\0')
{
HashVal += *Key++;
}
return HashVal % Tablesize;
}
struct ListNode
{
int Element;
Position Next;
};
typedef Position List;
struct HashTbl
{
int TableSize;
List *TheLists;
};
//Function to find next prime number for the size
bool isPrime(int n)
{
if(n <= 1)
{
return false;
}
if(n <= 3)
{
return true;
}
if(n%2 == 0 || n%3 == 0)
{
return false;
}
for(int i = 5; i*i <= n; i = i + 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int NextPrime(int N)
{
if(N <= 1)
{
return 2;
}
int prime = N;
bool found = false;
while(!found)
{
prime++;
if(isPrime(prime))
{
found = true;
}
}
return prime;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if(TableSize < MinTableSize)
{
printf("Table size is too small\n");
return NULL;
}
H = malloc(sizeof(struct HashTbl));
if(H == NULL)
{
printf("Out of space\n");
return NULL;
}
H->TableSize = NextPrime(TableSize);
H->TheLists = malloc(sizeof(List) * H->TableSize);
if(H->TheLists == NULL)
{
printf("Out of space\n");
return NULL;
}
for(i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = malloc(sizeof(struct ListNode));
if(H->TheLists[i] == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
H->TheLists[i]->Next = NULL;
}
}
return H;
}
//funtion to find the value
Position Find(const char *Key, HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(Key, H->TableSize)];
P = L->Next;
while(P != NULL && P->Element != Key)
{
P = P->Next;
}
return P;
}
void Insert(const char *Key, HashTable H)
{
Position Pos;
Position NewCell;
List L;
Pos = Find(Key, H);
if(Pos == NULL)
{
NewCell = malloc(sizeof(struct ListNode));
if(NewCell == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Next;
NewCell->Element = Key;
L->Next = NewCell;
printf("Key inserted\n");
}
}
else
{
printf("Key already exist\n");
}
}
int main()
{
char Name[6][20] = {"Joshua", "Erica", "Elizabeth", "Monica", "Jefferson", "Andrian"};
int Size = sizeof(Name[0])/sizeof(Name[0][0]);
HashTable H = InitializeTable(Size);
Insert(Name[0], H);
Insert(Name[1], H);
Insert(Name[2], H);
Insert(Name[3], H);
}
The putout of this code is:
Key inserted
Key inserted
This means, it only successfully inserted two keys, while the other name has not been inserted. I think there's some error in my Insert() function, but I got no clue. I tried using an online compiler and it compile properly.

Linked List pointers prob

I do not know why this is not working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// struct of list
typedef struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
} * liste;
int random(int a, int b)
{
return (a + (rand() % ((b + 1) + a)));
}
void initialisation(liste* LBO)
{
*LBO = NULL;
}
I think it's here the problem when I create q (q is created to point to the previous node).
void creation(liste* LBO)
{
liste q, prec = NULL;
int i = 0;
srand(time(NULL));
while (i < 3)
{
printf("%d", i);
q = malloc(sizeof(liste));
if (*LBO == NULL)
{
q->adresse = 0;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->suivant = *LBO;
*LBO = q;
i++;
}
else
{
prec = *LBO;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->adresse = prec->adresse + prec->taille;
q->suivant = *LBO;
*LBO = q;
i++;
}
}
}
void affichage(liste LBO)
{
printf("\nvoici ta liste \n ");
while (LBO != NULL)
{
printf("%d-->", LBO->taille);
LBO = LBO->suivant;
}
if (LBO == NULL)
printf("NULL");
}
int main()
{
// or here
printf("Hello world!\n");
liste LBO;
initialisation(&LBO);
creation(&LBO);
affichage(LBO);
return 0;
}
There are several issues:
Instead of calling
initialisation(&LBO);
which is not really wrong, just write:
LBO = NULL;
Then don't hide pointers with typedefs, it only adds confusion.
Instead of:
typedef struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
} *liste;
Write:
struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
};
and use struct noeud* instead of liste.
Now the real problem:
This is wrong. Here you allocate the size for a pointer, but you need to allocate the size for the whole structure:
q = malloc(sizeof(liste));
which is actually the same as:
q = malloc(sizeof(struct noeud*))
but you need:
q = malloc(sizeof(struct noeud))
You see now why hiding pointers with typedefs is a bad idea.
So here is the corrected version of your program (#includes ommitted for brevity):
struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
};
int random(int a, int b)
{
return (a + (rand() % ((b + 1) + a)));
}
void creation(struct noeud** LBO)
{
struct noeud* q, *prec = NULL;
int i = 0;
// srand(time(NULL)); <<<<< don't call srand here, call it once at the
// beginning of the program
while (i < 3)
{
printf("%d", i);
q = malloc(sizeof(struct noeud));
if (*LBO == NULL)
{
q->adresse = 0;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->suivant = *LBO;
*LBO = q;
i++;
}
else
{
prec = *LBO;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->adresse = prec->adresse + prec->taille;
q->suivant = *LBO;
*LBO = q;
i++;
}
}
}
void affichage(struct noeud* LBO)
{
printf("\nvoici ta struct noeud* \n ");
while (LBO != NULL)
{
printf("%d-->", LBO->taille);
LBO = LBO->suivant;
}
// if (LBO == NULL) <<<<<<<<<<< drop this, LBO is always NULL here
// but it doesn't hurt, it's just useless
printf("NULL");
}
int main()
{
srand(time(NULL)); // <<<<<<<<<<<<< call srand here
struct noeud* LBO;
LBO = NULL;
creation(&LBO);
affichage(LBO);
return 0;
}
There is still room for improvement, especially the creation function is somewhat awkward.
Also look at the comments with <<<<<<<<<<<, there are minor corrections

Resources