Wins the offer - a common node of the list

Title Description

Two input lists, find their first common node.

 

Thinking

Violence: use a stack to store

Improvement: For two lists, all nodes of all encounter the first node is the same because there is only one node next.

Get the length of the first two lists, then a pointer to one pair of fast and slow

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, head1, head2):
        len1 = 0
        len2 = 0
        start1 = head1
        start2 = head2
        while head1:
            len1+=1
            head1 = head1.next
        while head2:
            len2+=1
            head2 = head2.next
        
        if len2>len1:
            for i in range(len2-len1):
                start2 = start2.next
        elif len1>len2:
            for i in range(len1-len2):
                start1 = start1.next
        while start1 and start2:
            if start1==start2:
                return start1
            start1 = start1.next
            start2 = start2.next
        return None
            

 

Published 82 original articles · won praise 2 · Views 4356

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104815041