Reputation: 11
Actually the title is pretty self explanotary, I implement the linkedlist in online C compiler and the code correctly adds elements to the list, prints the list and then deletes the last element of the linkedlist. But when I compile the program in MinGW on cmd it enters a infinite loop, it doesn't even show the elements added just some random numbers looping and I haven't been able to pin-point the problem.
#include <stdlib.h>
typedef struct node{
int data ;
struct node *next ;
}node;
//
node* newNode(int value){
node *n = malloc(sizeof(node));
n->data = value;
n->next = NULL;
}
//
typedef struct list{
node *head;
node *tail;
}list;
//
list* add(list *liste, int value){
node *n = newNode(value);
if(liste->tail == NULL){
liste->tail = n;
}
n->next = liste->head;
liste->head = n;
return liste;
}
//
void gez(list *liste){
node *ix = liste->head;
while(ix != NULL){
printf("%d\n",ix->data);
ix = ix->next;
}
}
//
list* cikar(list *liste){
node *ix = liste->head;
while (ix->next != liste->tail){
ix = ix->next;
}
liste->tail = ix;
ix->next = NULL;
return liste;
}
//
int main(){
list *l = malloc(sizeof(list));
l = add(l,4);
l = add(l,8);
l = add(l,16);
gez(l);
l = cikar(l);
printf("\n");
gez(l);
return 0;
}
Upvotes: 0
Views: 88
Reputation: 130
Your code has several bugs:
head
and tail
have no initial value. This will cause indefinite behaviour in add
. Change malloc
to calloc
will by default NULL initialize them or you have to manually do so.newNode
has no return value. Return n
.ix->next = NULL
free(ix->next)
.Upvotes: 1