DEV Community

Thivyaa Mohan
Thivyaa Mohan

Posted on

4 3

160. Intersection of Two Linked Lists - Leetcode

Naive Approach :

  1. Find the length of both the lists
  2. Find the difference in the length of both the lists
  3. Then start checking the equality for the nodes
  4. Once we find equal node return that node
  5. otherwise if we reach at the end return the null

There is a better way to do it:

  1. We are going to traverse the shorter one and longer one at the same time
  2. We are going to set pointers to the heads of both of these.
  3. When we get at the end of the shorter one, we set the pointer to the head of the longer one.
  4. When we get at the end of the longer one, we set the pointer to the head of the shorter one.

Here, is the code of the implementation

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

        if(headA == NULL|| headB == NULL) return NULL;
        ListNode*a_pointer = headA;
        ListNode*b_pointer = headB;

        //while the nodes are not equal 
        while(a_pointer != b_pointer ){
            if(a_pointer == NULL){
              //this means it is at the end of the list 
                a_pointer = headB;   
            } 

        else{
            a_pointer = a_pointer->next;
        }

              if(b_pointer == NULL){
               //this means it is at the end of the list 
                b_pointer = headA;   
              } 

        else{
            b_pointer = b_pointer->next;
        }
        }
        return a_pointer;
    }
};
Enter fullscreen mode Exit fullscreen mode

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

AWS Industries LIVE! Stream

Watch AWS Industries LIVE!

Watch Industries LIVE! to find out how the AWS cloud helps solve real-world business challenges.

Learn More

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay