美文网首页
两个链表的第一个公共结点

两个链表的第一个公共结点

作者: 九日火 | 来源:发表于2021-01-09 15:04 被阅读0次

输入两个链表,找出它们的第一个公共结点。

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def FindCommonNode(self, pHead1, pHead2):
        nLength1 = self.GetLength(pHead1)
        nLength2 = self.GetLength(pHead2)
        nDiff = abs(nLength1 - nLength2)
        if nLength1 >= nLength2:
            nLong = pHead1
            nShort = pHead2
        else:
            nLong = pHead2
            nShort = pHead1

        for i in range(nDiff):
            nLong = nLong.next


        while nLong != None and nShort != None and nLong.val != nShort.val:
            nLong = nLong.next
            nShort = nShort.next

        return nLong




    def GetLength(self, pHead):
        nLength = n
        while pHead != None:
            pHead = pHead.next
            nLength += 1

        return nLength
package main


type ListNode struct {
    Val     int
    Next    *ListNode
}

func GetCommonNode (l1, l2 *ListNode) *ListNode {
    nLength1 := GetLength(l1)
    nLength2 := GetLength(l2)
    if nLength1 > nLength2 {
        nDiff := nLength1 - nLength2
        nLong := l1
        nShort := l2    
    } else {
        nDiff := nLength2 - nLength1
        nLong := l2
        nShort := l1
    }

    for i:=0; i<nDiff; i++ {
        nLong = nLong.Next
    }

    for nLong != nil && nShort != nil && nLong.Val != nShort.Val {
        nLong = nLong.Next
        nShort = nShort.Next
    }

    return nLong
}

func GetLength (l1 *ListNode) int {
    if l1.Val == nil {
        return 0
    }
    count := 0
    for l1 != nil {
        l1 = l1.Next
        count++
    }
    return count
}


func firstCommonMap(h1, h2 *LinkNode) *LinkNode {
    m := make(map[*LinkNode]bool)
    for h1 != nil {
        m[h1] = true
        h1 = h1.Next
    }

    for h2 != nil {
        if _, ok := m[h2]; ok {
            return h2
        }
        h2 = h2.Next
    }
    return h2
}

相关文章

网友评论

      本文标题:两个链表的第一个公共结点

      本文链接:https://www.haomeiwen.com/subject/qppxaktx.html