📑 题目:160. 相交链表

🚀 本题 LeetCode 传送门

题目大意

找到 2 个链表的交叉点。

解题思路

这道题的思路其实类似链表找环。

给定的 2 个链表的长度如果一样长,都从头往后扫即可。如果不一样长,需要先“拼成”一样长。把 B 拼接到 A 后面,把 A 拼接到 B 后面。这样 2 个链表的长度都是 A + B。再依次扫描比较 2 个链表的结点是否相同。

代码

  1. package leetcode
  2. import ""fmt""
  3. /**
  4. * Definition for singly-linked list.
  5. * type ListNode struct {
  6. * Val int
  7. * Next *ListNode
  8. * }
  9. */
  10. func getIntersectionNode(headA, headB *ListNode) *ListNode {
  11. //boundary check
  12. if headA == nil || headB == nil {
  13. return nil
  14. }
  15. a := headA
  16. b := headB
  17. //if a & b have different len, then we will stop the loop after second iteration
  18. for a != b {
  19. //for the end of first iteration, we just reset the pointer to the head of another linkedlist
  20. if a == nil {
  21. a = headB
  22. } else {
  23. a = a.Next
  24. }
  25. if b == nil {
  26. b = headA
  27. } else {
  28. b = b.Next
  29. }
  30. fmt.Printf(""a = %v b = %v
  31. "", a, b)
  32. }
  33. return a
  34. }