C# solution: get two counts then longer one goes diff steps then compare


  • 0
    B
    public class Solution
    {
    	public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
    	{
    		if (headA == null || headB == null) return null;
    
    		var curA = headA;
    		var countA = 0;
    
    		while (curA != null)
    		{
    			countA++;
    			curA = curA.next;
    		}
    
    		var curB = headB;
    		var countB = 0;
    
    		while (curB != null)
    		{
    			countB++;
    			curB = curB.next;
    		}
    
    		var diff = Math.Abs(countA - countB);
    
    		curA = headA;
    		curB = headB;
    
    		if (countA > countB)
    		{
    			while (diff > 0)
    			{
    				curA = curA.next;
    				diff--;
    			}
    		}
    		else
    		{
    			while (diff > 0)
    			{
    				curB = curB.next;
    				diff--;
    			}
    		}
    
    		while (curA != null && curA != curB)
    		{
    			curA = curA.next;
    			curB = curB.next;
    		}
    
    		return curA;
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.