c - Linked list is throwing an infinite loop, yet latest pointer is set to null -
i've written linked list , when i'm doing append end, seems going infinite loop.
// function make node , give value @ end of list void add_at_end(struct node* begin, int v) { // new node struct node* temporary = begin; // pointer start of list temporary->vv = v; temporary->nx = null; // latest node if (begin == null) { // make new list if empty begin = temporary; return; } struct node* iterate = begin; while (iterate->nx != null) { iterate = iterate->nx; } iterate->nx = temporary; return; } i call using:
struct node alpha; add_at_end(&alpha, 1); why throwing infinite loop?
alphanot initalized, contains garbage, including next pointer. access content undefined behaviour, result in infinite loop... or crash.. or whatever.begin = temporary;set variable in local scope, , won't have effect on you've passed function. either pass pointer pointer (**), or pass existing node function (in case there's no need check). doing mix of these doesn't make sense.- it's inefficient traverse whole list add element. should maintain link last node, becomes o(1) operation.
Comments
Post a Comment