0

I am trying to merge two linked lists. It works correctly when I write this:

if(p->data < q->data){
                third = p;
                last = p;
                p = p->next;
                third->next = NULL;
        }else{
                third = q;
                last = q;
                q = q->next;
                third->next = NULL;
        }

But it doesn't work correctly when I write this:

if(p->data < q->data){
                third = p;
                last = p;
                third->next = NULL;
                p = p->next;
        }else{
                third = q;
                last = q;
                third->next = NULL;
                q = q->next;
        }

I am wondering why. Can anyone explain? third: Pointer from where merged list starts. p, q: Pointers to 2 lists. last: Pointer which connects further elements.

  • See https://stackoverflow.com/questions/9224517/what-are-classes-references-and-objects. It is about Java but the principles there are the same as what's confusing you. You're overwriting `p->next` when you say `third->next = NULL;` in the second example, which is why it's not working. `third` and `p` point to the same location in memory. – Welbog Nov 11 '21 at 02:16
  • So what happens to third when I say p = p->next? – Nikhil Karve Nov 11 '21 at 16:51
  • Nothing. `p` and `third` are different variables that point to the same location memory. When you overwrite `p` with `p->next`, `third` doesn't change. – Welbog Nov 11 '21 at 17:27
  • Then why does it matter if I do third->next=NULL before p=p->next? – Nikhil Karve Nov 11 '21 at 17:59
  • Because `third` and `p` point to the same object, so `third->next` and `p->next` are the same thing, until you execute `p=p->next`. – Welbog Nov 11 '21 at 20:01
  • Does that mean code is seperating whatever third is pointing at? – Nikhil Karve Nov 11 '21 at 21:22
  • I don't understand the question. – Welbog Nov 12 '21 at 02:36

0 Answers0