Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

LC 160. Intersection of Two Linked Lists 相交链表

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func getIntersectionNode(headA, headB *ListNode) *ListNode {
    lA := getLength(headA)
    lB := getLength(headB)
    
    if lB < lA {
        headA, headB = headB, headA
        lA, lB = lB, lA
    }
    
    for i := 0; i < lB-lA; i++ {
        headB = headB.Next
    }
    
    for headA != headB {
        headA = headA.Next
        headB = headB.Next
    }
    
    return headA
}

func getLength(head *ListNode) int {
    l := 0
    for head != nil {
        l++
        head = head.Next
    }
    return l
}

交替行走法

待复习

逻辑上分析「A+B」和「B+A」两条链表,找到公共节点https://singee.atlassian.net/wiki/spaces/MAIN/pages/49316106/Week+41+2024#LC-160.-Intersection-of-Two-Linked-Lists-%E7%9B%B8%E4%BA%A4%E9%93%BE%E8%A1%A8%EF%BC%88%E5%88%A4%E6%96%AD%E4%B8%A4%E4%B8%AA%E9%93%BE%E8%A1%A8%E6%98%AF%E5%90%A6%E7%9B%B8%E4%BA%A4%EF%BC%89

 

  • No labels