intersection of two given LinkedList

295 Views Asked by At

Find the intersection of two given LinkedList (where each node has a character). Return the LinkedList which has character which appears in both LinkedList (same sequence order as LinkedList1).

error:variable temp might not have been initialized

I tried a lot to resolve this error, but I cant step forward in this problem. Please help to resolve my error.

public SchNode func(SchNode head1, SchNode head2)
    {
        SchNode temp;

    for(SchNode ptr=head1;ptr!=null;ptr=ptr.nextNode)
    {
        for(SchNode ptr2=head2;ptr2!=null;ptr2=ptr2.nextNode)
        {
            if(ptr.ch==ptr2.ch)
            {
           temp.ch=ptr2.ch;
           temp=temp.nextNode;

            }
        }
    }

    return temp ;
    }
1

There are 1 best solutions below

1
On

You can use this method if don't understand it wrong.

  • measure list1 length, lets call it A
  • measure list2 length, lets call it B
  • difference is: C = A - B
  • if C < 0 then choose list2, else choose list1, lets call chosen list choosenList
  • answer is choosenList[abs(C)] //i mean absolute value of C

EDIT: what i understand is you have two linked lists that have a common node(pointer)