Leetcode 160. Intersection of Two Linked Lists

twisted-fate發表於2019-05-25

刷了一道簡單的

pesudo code :

get head a len
get head b len

if a>b
    gap=a-b
    while not end 
        a two step ahead start , b start
        if node equal
            return node

if b>a
    gap=b-a
    while not end
        b two step ahead 

solution1 : (最容易想到的解法,但不是最優)

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func getIntersectionNode(headA, headB *ListNode) *ListNode {
    if headA==nil || headB==nil {
        return nil
    }

    aLen :=1
    node:=headA
    for node!=nil {
        node=node.Next
        aLen++
    }

    bLen :=1
    node=headB
    for node!=nil {
        node=node.Next
        bLen++
    }

    var node1 *ListNode
    var node2 *ListNode
    var gap int

    if aLen>bLen {
        gap=aLen-bLen
        node1=headA
        for i:=1;i<=gap;i++{
            node1=node1.Next
        }
        node2=headB
    } else {
        gap=bLen-aLen
        node1=headB
        for i:=1;i<=gap;i++{
            node1=node1.Next
        }
        node2=headA
    }

    for node1!=nil {
        if node1==node2 {
            return node1
        }
        node1=node1.Next
        node2=node2.Next

    }

    return nil

}

solution2 : (看了Discuss vote 最多的解法後寫的)

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章