Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
122 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
--- | ||
weight: 160 | ||
|
||
bookFlatSection: true | ||
|
||
BookToC: true | ||
|
||
title: "160. 相交链表" | ||
--- | ||
|
||
# 160. 相交链表 | ||
|
||
## 题目地址 | ||
|
||
+ [力扣](https://leetcode.cn/problems/intersection-of-two-linked-lists/) | ||
+ [LeetCode](https://leetcode.com/problems/intersection-of-two-linked-lists/) | ||
|
||
## 解题思路 | ||
|
||
如果两个链表相交,那么相交点之后的长度是相同的。 | ||
|
||
所以,我们需要做的事情是,让两个链表从**距离末尾同等距离的位置**开始遍历。而这个位置只能是较短链表的头结点位置。为此,需要求出两个链表的长度并消除两个链表的长度差。 | ||
|
||
## 具体实现 | ||
|
||
{{< tabs "uniqueid" >}} | ||
|
||
{{< tab "Go" >}} | ||
|
||
```go | ||
package main | ||
|
||
import "fmt" | ||
|
||
type ListNode struct { | ||
Next *ListNode | ||
Val int | ||
} | ||
|
||
func getIntersectionNode(headA, headB *ListNode) *ListNode { | ||
if headA == nil || headB == nil { | ||
return nil | ||
} | ||
|
||
var ( | ||
currA, currB = headA, headB | ||
lenA, lenB int | ||
) | ||
// 计算链表的长度 | ||
for currA != nil { | ||
lenA++ | ||
currA = currA.Next | ||
} | ||
|
||
for currB != nil { | ||
lenB++ | ||
currB = currB.Next | ||
} | ||
|
||
currA, currB = headA, headB | ||
|
||
// 判断谁是最长的,把最长的赋值给 currA | ||
gap := 0 | ||
if lenA >= lenB { | ||
gap = lenA - lenB | ||
} else { | ||
gap = lenB - lenA | ||
currA, currB = currB, currA | ||
} | ||
|
||
for gap > 0 { // 移动最大的位置 | ||
currA = currA.Next | ||
gap-- | ||
} | ||
|
||
// 同时移动 | ||
for currA != nil { | ||
if currA == currB { | ||
return currA // 这里 return currB 也行 | ||
} | ||
currA = currA.Next | ||
currB = currB.Next | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func main() { | ||
t := &ListNode{ | ||
Next: &ListNode{ | ||
Next: nil, | ||
Val: 9, | ||
}, | ||
Val: 8, | ||
} | ||
|
||
ca := &ListNode{ | ||
Next: &ListNode{ | ||
Next: t, | ||
Val: 2, | ||
}, | ||
Val: 1, | ||
} | ||
|
||
cb := &ListNode{ | ||
Next: &ListNode{ | ||
Next: &ListNode{ | ||
Next: t, | ||
Val: 5, | ||
}, | ||
Val: 4, | ||
}, | ||
Val: 3, | ||
} | ||
ret := getIntersectionNode(ca, cb) | ||
fmt.Println(ret) | ||
} | ||
|
||
``` | ||
{{< /tab >}} | ||
|
||
{{< /tabs >}} |