c - I get into a endless loop in linked list -


i want find out intersect between 2 linked list sorted,but endless loop ,i know set wrong condition after while don't know how fix that. pls me.

#include<stdio.h> #include<stdlib.h> typedef struct node {     int data;     struct node *next; }list;  list *intersect(list *l1, list *l2) {     list *result;     list *l1pos, *l2pos, *resultpos;      l1pos = l1;     l2pos = l2;     result = (list *)malloc(sizeof(list));     resultpos = result;     while(l1pos != null && l2pos != null) {         //endless loop         if(l1pos->data < l2pos->data) {             l1pos = l1pos->next;         } else if(l1pos->data > l2pos->data) {             l2pos = l2pos->next;         } else {             resultpos->data = l1pos->data;             l1 = l1pos->next;             l2 = l2pos->next;             resultpos->next = (list *)malloc(sizeof(list));             resultpos = resultpos->next;         }     }      return result; } 

when find intersection, don't change values of l1pos , l2pos, loop keeps choosing final else statement forever.

if want end loop, use break or set 1 of mentioned variables null.

otherwise can set both nodes next node , let loop continue until end of list:

l1pos = l1pos->next; l2pos = l2pos->next; 

also allocation of result questionable, since node allocated before known if loop found result, return node contain uninitialized values, , final node in list result contain uninitialized values. instead of allocating in advance, allocate when find node, , set next pointer of new node null list terminated. in case nothing found, function return result, null (as initialized null before loop).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -